Access-Control-Allow-Origin Error..(using cordova) - javascript

I'm trying to web server and client..(Hybrid app! using cordova)
But Access-Control-Allow-Origin error..so I downloaded chrome extension program cors.. but doesn't working..
[server.js]
var app = require('express')();
var http = require('http').Server(app);
var cors = require('cors');
var io = require('socket.io')(http);
// io.set('origins','*:*');
io.on('connection', function(socket){
console.log('a user connected');
socket.on('weather_location', function(msg){
socket.emit('message', msg);
})
});
http.listen(80, function(){
console.log('listening on *:3737');
});
[index.html]
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<html>
<head>
<title>location_weather</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<!-- <script type='text/javascript' src='/socket.io/socket.io.js'></script> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.slim.js"/>
<!-- <script type="text/javascript" src="./js/socket.io.js"/> -->
<script type="text/javascript" src="https://openapi.map.naver.com/openapi/v3/maps.js?clientId=irru1vaga0dOPnfgy29o&submodules=geocoder"></script>
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src ws://example.com wss://example.com"> -->
</head>
<body>
<button id="weatherBtn" onclick="weather_location();">클릭</button>
</body>
</html>
<script>
var socket = io.connect('http://202.31.200.138:80');
//var socket = io();ttp
$(function (){
//var socket = io.connect('http://202.31.200.138:3330');
socket.on('message', function(data){
console.log(data);
alert(data);
});
});
function weather_location(){
alert("hello");
socket.emit('weather_location','message');
}
// function location_weather(){
// if(navigator.geolocation){
// navigator.geolocation.getCurrentPosition(function(position){
// alert("위도 : " + position.coords.latitude + "tt" + position.coords.longitude);
// }, function(error){
// console.error(error);
// },{
// enableHighAccuracy : false,
// maximumAge : 0,
// timeout : Infinity
// });
// socket.emit('weather_location',position.coords.latitude );
// } else {
// alert("GPS를 지원하지 않습니다.");
// }
// //return false;
// }
</script>
[error]
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Please Help me...

You need to add the whitelist plugin,
https://github.com/apache/cordova-plugin-whitelist
In config.xml add
<!-- will not stop any calls -->
<access origin="*" />

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
You can use like this also , may be it will help.

This might be related to chrome issue if your cordova is using chrome as a default browser of webview. I've encounter the issue on v76.0.3809.89 of chrome and updating to v76.0.3809.111 solved the Access-Control-Allow-Origin issue.

Try using the cors in you app middleware
app.use(cors());

Related

Inconsistent HTTP trigger behaviour to Firebase Cloud Functions

I'm having trouble reliably triggering a Firebase Cloud Function via the HTTP trigger method. It doesn't work in all browsers, and sometimes only works if you reload the page. The html webpage is hosted with Firebase Hosting.
Premise is simple, main html page has a button which when pressed, sends the HTTP request to the Cloud Function, and then navigates to another page saying done. The Cloud Function sends an FCM notification and works reliably when manually using the HTTP request url.
Is there something wrong with my HTTP request in scripts.js? What would make this very inconsistent behaviour? It works generally in Chrome, not in Firefox, and sometimes in Edge.
index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel=icon href=favicon.ico>
<title>Title</title>
</head>
<body>
<h1>New heading</h1>
<input type="button" value="Send FCM" onclick="doThing()">
<script src="scripts.js"></script>
</body>
</html>
scripts.js looks like this
var request = require('request')
function doThing(){
const url = '<HTTP request URL>';
request(url, function(error, response, body){
if (!error && response.statusCode == 200){
window.location.href = "outro.html";
}
})
}
and outro.html looks like this;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<body>
<h1>Cya</h1>
</body>
</body>
</html>
For clarity, this is the Cloud Function script:
const functions = require('firebase-functions');
const admin = require('firebase-admin')
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.https.onRequest((request, response) =>{
var topic = 'all';
var payload = {
notification:{
title: 'Title!',
body: 'Test!'
},
};
return admin.messaging().sendToTopic(topic, payload).then((res) =>{
response.status(200).send("ok");
return console.log("Success:");
}).catch((err) =>{
console.log("Error: ", err);
response.status(500).send("bad");
});
});
All are deployed with firebase deploy.

I encountered a problem while doing this example from the book 'Beginning Node.JS'. The aim is to setting up requireJS

My File Structure -
> client-
> -app.js
> index.html
> require.js
> server.js
server.js - to create a basic http server
const http = require('http'),
fs = require('fs');
function send404(response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('Error 404: Resource not found.');
response.end();
}
const server = http.createServer( (req,res) => {
if(req.method == 'GET' && req.url == '/')
{
res.writeHead(200, {'content-type': 'text/html'});
fs.createReadStream('index.html').pipe(res);
}
else
{
send404(res);
}
}).listen(3000);
console.log('server running on port 3000');```
index.html
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello There</title>
<script
src="require.js"
data-main="client/app.js">
</script>
</head>
<body>
<p>Press Ctrl + Shift + J (windows) or CMD + Opt + J (MacOSX) to open up the console.</p>
</body>
</html>
```
app.js
console.log('Hello RequireJS!');
I am supposed to get Hello RequireJS! as output in the chrome developer tools console.
But, i get 3 errors as shown below:
1.
Denying load of
chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/app.js. Resources
must be listed in the web_accessible_resources manifest key in order
to be loaded by pages outside the extension.
2.
GET http://localhost:3000/require.js net::ERR_ABORTED 404 (Not Found)
3.
GET chrome-extension://invalid/ net::ERR_FAILED
Please tell me if you have also encountered this problem and how to solve this.
Thanks.
`

How to use Cordova InAppBrowser into a HostedWebApps?

I have a website with 2 mobile-apps displayed with Cordova, and they works really great. But I have a problem :
When an external link is triggered by the user, he go out of the application and don't have any possibility to come back on the App... (except close and reopen).
I have installed inappbrowser according to this tutorial. Sounds very simple but not working...
Console :
cordova plugin add cordova-plugin-inappbrowser
Link (supposed to trigger InAppBrowser - not working) :
www.google.com
And I just remembered, that my apps are displayed with a technique named Hosted Web App. And maybe it's what InAppBrowser does not work : we are already in a webbrowser ?!
I will snip my config & js code bellow, here's the tutorial of Microsoft who helped me on the App setting.
Goal : find a way to use InAppBrowser, because we have a lot of external links in our website.
Any ideas please ?
Many thanks !
Here is the code :
Index.js
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
app.receivedEvent('deviceready');
// Here, we redirect to the web site.
var targetUrl = "https://www.website.test/";
var bkpLink = document.getElementById("bkpLink");
bkpLink.setAttribute("href", targetUrl);
bkpLink.text = targetUrl;
window.location.replace(targetUrl);
},
// Note: This code is taken from the Cordova CLI template.
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
App.js
/*global app, $on */
(function () {
'use strict';
/**
* Sets up a brand new Todo list.
*
* #param {string} name The name of your new to do list.
*/
function Todo(name) {
this.storage = new app.Store(name);
this.model = new app.Model(this.storage);
this.template = new app.Template();
this.view = new app.View(this.template);
this.controller = new app.Controller(this.model, this.view);
}
var todo = new Todo('todos-vanillajs');
function setView() {
todo.controller.setView(document.location.hash);
}
$on(window, 'load', setView);
$on(window, 'hashchange', setView);
var onSuccess = function(position) {
var geotext = document.getElementById('geotext');
geotext.textContent = 'Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude;
};
var onError = function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
var button = document.getElementById('geo');
button.addEventListener("click", function(){
navigator.geolocation.getCurrentPosition(onSuccess, onError);
});
function myOnDeviceReady() {
if (navigator.connection.type == Connection.NONE) {
navigator.notification.alert('An internet connection is required to continue');
} else {
window.location="https://www.website.test/";
}
}
document.addEventListener("deviceready", myOnDeviceReady, false);
})();
Index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="viewport-fit=cover, initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://www.website.test/ https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<title>mysite</title>
<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
<link rel="stylesheet" type="text/css" href="css/overrides.css" />
</head>
<a id="bkpLink" href="https://www.website.test/" class="mysite_font">mysite</a>
<div class="app">
<img src="img/logo_gradient.png" style="width: 200px;">
<div id="deviceready" class="blink">
<p class="mysite_font event listening">Chargement de l'app...</p>
<p class="mysite_font event received">Chargement...<br/>Merci de patienter quelques instants.</p>
</div>
</div>
<script type="text/javascript" src="scripts/index.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script src="node_modules/todomvc-common/base.js"></script>
<script src="js/helpers.js"></script>
<script src="js/store.js"></script>
<script src="js/model.js"></script>
<script src="js/template.js"></script>
<script src="js/view.js"></script>
<script src="js/controller.js"></script>
<script src="js/app.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</html>
From your question and follow ups, I'm assuming you are loading in yourwebsite.com into your mobile app, then on yourwebsite.com you want to open external links but keep otherwebsite.com within your app. If I'm understanding correctly, you can load yourwebsite.com in your mobile app and open external links with inAppBrowser by sending a postMessage() back to your mobile app with the external link.
First, loading in yourwebsite.com within an <iframe> on your mobile app:
<iframe src="https://www.yourwebsite.com">
On yourwebsite.com, when an external link is clicked (in my example, this anything with . external_url class and you'll most likely have to use querySelectorAll instead for multiple links), capture it with JS and send the href value back to the mobile app with postMessage():
document.querySelector('.external_url').addEventListener('click', function(event) {
event.preventDefault(); // stops the user from loading this link
var data = {'external_url': event.target.href};
window.parent.postMessage(data, '*');
});
Back on your mobile app, you need to listen to incoming postMesssage(). And trigger inAppBrowser to open the external url that was passed back from yourwebsite.com.
window.addEventListener('message', function(event) {
if (event.data.external_url) {
window.cordova.InAppBrowser.open(event.data.external_url, '_blank', 'location=no');
}
}, true);
I have not tested this code, but it should get you pointed in the right direction with a few changes.

Spotify Implicit Grant won't work on node

I am trying to make the codes you see here:
https://glitch.com/edit/#!/amusing-swallow?path=index.html:7:68
executable on my node js application. Please note that the codes on that link is working.
What I did is that I set up an environment like this:
root folder
--public
--index.html
--script.js
--app.js
--package.json
And then I copied the html code to my index.html file like this:
<!DOCTYPE html>
<html>
<head>
<title>Spotify Implicit Grant Template</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://sp-bootstrap.global.ssl.fastly.net/8.0.0/sp-bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body class="container">
<h1 class="text-salmon">Spotify Implicit Grant Template</h1>
<h3>This app uses the implicit grant authorization flow to authenticate users and get user data.</h3>
<p>
Here are your top artists on Spotify:
<ol id="top-artists"></ol>
</p>
<script src="../script.js" type='text/javascript'></script>
</body>
</html>
Nothing special and then I made the script.js a self invoking function like this:
(function() {
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
// Set token
let _token = hash.access_token;
const authEndpoint = "https://accounts.spotify.com/authorize";
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = "xxxxxxxxxxxxxxxxxxxxxxxx";
const redirectUri = "http://localhost:8888/callback/";
const scopes = ["user-top-read"];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join(
"%20"
)}&response_type=token&show_dialog=true`;
}
// Make a call using the token
$.ajax({
url:
"https://api.spotify.com/v1/search?query=tania+bowra&offset=0&limit=20&type=artist",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + _token);
},
success: function(data) {
// Do something with the returned data
data.items.map(function(artist) {
let item = $("<li>" + artist.name + "</li>");
item.appendTo($("#top-artists"));
});
}
});
})();
And then finally on my app.js for express:
var express = require("express"); // Express web server framework
var app = express();
app.use(express.static(__dirname + "/public"));
console.log("Listening on host 8888......");
app.listen(8888);
So I tried to run this and whenever I visit the localhost:8888, I keep on getting these:
GET http://localhost:8888/script.js 404 (Not Found)
Refused to execute script from 'http://localhost:8888/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I am not sure why. But I just copied the same exact code and just put my credentials there but it won't still work. Any idea what am I doing wrong?

CordovaFileTransfer | How put string from the headers to TargetPath?

I have project write with Ionic Framework and AngularJS.
His task is to download files from the URL, type as http://www.uzhnu.edu.ua/uk/infocentre/get/6500
The problem is that the examples of "how to download the file and give it a name" is only if the path to URL line have his name .
The name of my file does not have this name in url. It is in the headers of http request, here is screen made with POSTMAN, but how to get it and put in a variable TargetPath, I do not know. Can anyone suggest something?
Here is code of
FileTransferController.js:
app.controller('MyCtrl', function($scope, $cordovaFile, $cordovaDialogs, $window, $ionicLoading,$ionicPopup, $timeout, $cordovaFileTransfer) {
$scope.id = '6500';
$scope.downloadFile = function() {
$ionicLoading.show({template: 'Download file...'});
var url = "http://www.uzhnu.edu.ua/uk/infocentre/get/"+$scope.id;
var filename = $scope.id+".doc";
alert(filename);
var targetPath = "/storage/sdcard0/documents/" + filename;
var trustHosts = true;
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(entry) {
// Success!
$ionicLoading.hide();
console.log('download complete: ' + entry.toURL());
alert('File download: ' + targetPath);
}, function(error) {
$ionicLoading.hide();
// An error occured. Show a message to the user
alert('Sorry');
alert(JSON.stringify(error));
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
false,
{
headers: {
"Content-Disposition": ""
},
});
};
});
app.js:
var app = angular.module('starter', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- ng-cordova -->
<script src="js/ng-cordova.js"></script>
<script src="js/ng-cordova.js"></script>
<script src="js/ng-cordova.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/FileTransferController.js"></script>
</head>
<body ng-app="starter">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content ng-controller="MyCtrl">
<button class="button-positive" ng-click="downloadFile()">Download File</button>
</ion-content>
</ion-pane>
</body>
</html>
P.S. Code work only on real device. And must download all plugins:
ionic plugin add cordova-plugin-file
ionic plugin add cordova-plugin-file-transfer
and in folder "js" add file "ng-cordova.js" and "ng-cordova.min.js". DOwnload they can with:
bower install ngCordova
YES! Finally I did it!If someone will need a code, her ir is:
$scope.downloadFile = function() {
var url = "http://example.com/page";
$ionicLoading.show({template: 'Download file...'});
$http.get(url).
success(function (data, status, headers) {
var head = headers('Content-Disposition');
var filename = head.substr(head.lastIndexOf('=')+1);
alert(filename);
var targetPath = "/storage/sdcard0/documents/" + filename;
var trustHosts = true;
var options = {};
$cordovaFileTransfer.download(url, targetPath, options, trustHosts)
.then(function(entry) {
$ionicLoading.hide();
console.log('download complete: ' + entry.toURL());
alert('File download: ' + targetPath);
}, function(error) {
$ionicLoading.hide();
console.log('headers: ' + headers('Cache-Control'));
// An error occured. Show a message to the user
alert('Sorry');
alert(JSON.stringify(error));
})
alert(head1);
$ionicLoading.hide();
$scope.$broadcast('scroll.refreshComplete');
return(JSON.stringify(head1))
})
.error(function (status) {
alert(status);
$ionicLoading.hide();
$scope.$broadcast('scroll.refreshComplete');
});
};

Categories