Access-Control-Allow-Origin' header is present on the requested resource - angularjs

I am trying to login using google authentication using node.js, but it showing error like below.
XMLHttpRequest cannot load https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_ur…d=410427634474-u3tpasmj4r80s6v20o54s85fikhotl79.apps.googleusercontent.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Someone please help me to solve this, because i am trying this from past two days, still didn't fix.

Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});

Write this in app.get function.
res.set('Access-Control-Allow-Origin', '*');
You can use node function as
app.get("/png",function(req,res){
res.set('Access-Control-Allow-Origin', '*');
var sr = { data: "", message: "", error: "" };
console.log(222);
connection.query('SELECT * FROM png ', function(err, rows, fields) {
connection.end();
if (!err)
{
var userr = rows;
sr.data = userr;
res.json(sr);
} else{
console.log('Error while performing Query.');
}
});
});

Related

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost 'is therefore not allowed access

I want to fetch json data through URL passing. But It is showing an error like
Failed to load https://sample-dec42.firebaseapp.com/one.json: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access.
to solve this error I used the following server and controller code
controller:
$http.get('https://sample-dec42.firebaseapp.com/one.json').then( function(response) {
$scope.resultValue = response.data;
console.log('successful');
document.write(JSON.stringify(response));
console.log( $scope.resultValue);
});
app.js:
var request = require('request');
app.use(function(req,response,next)
{
response.header('Access-Control-Allow-Origin',"*");
response.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
response.header('Access-Control-Allow-Headers','Content-Type');
next();
})
Here Just,I created one sample fiddle: Click Here to View
how to resolve this error. I have searched in an internet. But, still i don't have an idea why i am getting this error again and again.
Thanks in advance.
Can you try this:
Import "cors" module to your project and if you are using Express just use it:
app.use(cors());
Use the following code::
app.use(function (req, res, next) {
// Following headers are needed for CORS
res.setHeader('access-control-allow-headers', 'Origin, X-Requested-With, Content-Type, Accept, ajax, access-key,backend,app_request,frontend, token,device');
res.setHeader('access-control-allow-methods', 'POST,HEAD,GET,PUT,DELETE,OPTIONS');
res.setHeader('access-control-allow-origin', '*');
next();
});

No 'Access-Control-Allow-Origin' header is present on the requested resource.

I've seen several questions and answers around this and mine is half working.
I have a node.js api server with url api.domain.com and the website on an nginx server at www.domain.com when I do the following in angular the request goes through on the api server, I see the request I see it getting parsed and put into the database. However, on the client side I do not get a return right away and then eventually I will see No 'Access-Control-Allow-Origin' header is present on the requested resource.
I know what is causing this behavior but shouldn't it throw the error before it hits the API server? Also note that the node.js server has cors enabled. The response that should be coming back is json.
$http({
method: 'POST',
url: "http://api.domain.com/addtrans/" + $scope.accountID,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
payload: JSON.stringify(trans)
}
}).success(function (result) {
$scope.trans = {};
console.log(result);
});
I have used the below middleware for all of our projects and it has been proven to work best.
const allowCors = (req, res, next) => {
/** Allow all origins, for now TODO */
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Authorization, Content-Type');
res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
/** Browser check for pre-flight request to determine whether the server is webdav compatible */
if ('OPTIONS' == req.method) {
res.sendStatus(204);
}
else next();
};
// Put this code before the routes you want to allow CORS to
app.use(allowCors);
You should change the Allow-Origin to something more restricted for security reasons.
The above code covers CORS as well as pre-flight on most browsers(this ia major issue we were having in the beginning).
i used this a while ago (express 3.x):
// npm install --save cors
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
app.use(express.static());
app.get('*', function(){});
require('http').createServer(app).listen(3000)
Remember that the cors header should be on the response which is coming from server not the request which is sent from client.
You can use a middleware to enable cors on the server:
//CORS middleware
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'example.com');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
//...
app.configure(function() {
...
app.use(allowCrossDomain);
...
});

Response to preflight request doesn't pass access control check with AngularJS

how can I solve this problem?
when I send POST request to the server...
XMLHttpRequest cannot load http://localhost:3000/data-search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
//myservice.js
function setNewSearch(titleParam, ratingParam) {
var data = {
title: titleParam,
rating: ratingParam
};
$http.post('http://localhost:3000/data-search', data).then(successCallback, errorCallback);
function successCallback(e){
console.log('successCallback ' + JSON.stringify(e));
}
function errorCallback(e){
console.log('errorCallback ' +JSON.stringify(e));
}
}
//my controller.js
$scope.newSearch = function(){
NewSearchService.setNewSearch('john', 'white');
};
//my server is :
app.post('/data-search', insertDataSearch);
function insertDataSearch(req, res) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
var newDataSearch = new dataSearch();
newDataSearch.title = req.param('title');
newDataSearch.rating = req.param('rating');
newDataSearch.save(function(err) {
if (err) {
console.log('Error in Saving newDataSearch: ' + err);
throw err;
}
res.send("Sucess");
});
}
this problem only occurs when I enter on $http.post the parameter 'data'
I think the problem could be that data is a JavaScript object and not valid JSON
try this in the setNewSearch() function
$http.post('http://localhost:3000/data-search', JSON.stringify(data)).then(successCallback, errorCallback);
Perhaps your handler is throwing an error or some other issue processing the data is preventing it from replying with the allow origin headers?

AngularJS POST request with JSON array data to Express server

I have a static AngularJS website and an Express server running on different domains. The site sends GET requests to the server with a file name as the parameter. The server then requests the file from an S3 bucket, that sends it with "binary/octet-stream" as the "Content-Type". It decrypts the data and sends it back to the site with the same "Content-Type", which then downloads the file. This all works well for single file requests, however I would like to be able to send the server an array of file names all at once, and then be able to download multiple files. I tried sending the file names as a JSON array but I get the error:
XMLHttpRequest cannot load http://localhost:3000/decrypt. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'file://' is therefore not allowed access.
In my server console, the request shows up as OPTIONS instead of POST. I've also made sure to include Access-Control-Allow-Origin: * in my response headers. How should I go about resolving this?
UPDATE:
I was able to resolve the CORS error by adding the following middleware on my router:
function allowCrossDomain(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.status(200).end();
}
else {
next();
}
}
However, I'm still not sure how to send multiple (for each file) "binary/octet-stream" in the response, and download them as files on the static site. Currently I am using angular-file-saver to save files from single requests.
You need to do a couple things in your server. First off are you using multer with bodyParser? Multer will allow you to add in post calls and will handle passing the data for you.
First AngularJS Post:
$http.post(baseUrl + "mypostmethod", o) //o is your object
.then(function successCallback(resp) {
console.log(resp)
}, function errorCallback(resp) {
console.log(resp)
});
Now as for your nodejs express setup, you want to ensure you are using all the proper modules. I will provide the basic list that I use in most of my projects. Also if you use req.headers.origin instead of * you sould no longer get the Access-Control-Allow-Origin error.
NodeJS:
var express = require('express'),
fs = require('fs'),
spdy = require('spdy'),
bodyParser = require('body-parser'),
multer = require('multer'),
helmet = require('helmet'),
upload = multer(), // this will allow you to pass your object into your post call with express
path = require('path'),
cookieParser = require('cookie-parser'),
request = require('request'),
app = express(),
http = require('http'),
formidable = require('formidable'); //Good for handling file uploads
app.use(helmet());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH');
res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
next();
});
These are the basic ones I use in almost all my programs. The most important with expressis bodyParser and multer since these will allow you to use your gets and post properly.
Here is an example of a post NodeJS:
app.post('/mypostmethod', upload.array(), function(req, res) {
var body = req.body,
sess = req.session;
res.send({
Status: "Success"
});
});
In this post when you use upload.array() that is utilizing multer and now req.body is the object you passed in with your angular post call.
Let me know if you have any question, I hope this helps.

AngularJs $http GET passing custom header returns 404

I've been reading many blogs about it and I could not figure it out how to solve my problem..
I need to pass a token as a custom header to a get $http.. I get an error 404 because the GET request turns into OPTIONS.
The nodejs API Rest is working properly as I test it with the chrome "rest console" app.
Thank you Kasper..
This was my server code before starting this thread..
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", 'X-Requested-With, Content-Type');
res.header('Access-Control-Allow-Methods', 'GET, POST', 'DELETE', 'PUT');
next();
});
With this server code, everytime I send a request (GET) from the client with AngularJS adding a custom header "token"
myapp.factory("Booking", function ($resource) {
return $resource(
serverUrl + "/agp/pricelist",
{}, //default parameters
{
"reviews": {'method': 'GET', 'params': {'reviews_only': "true"}, isArray: true,
headers: {'Content-Type':'application/json', 'token': 'diego' }}
}
);
});
So, when you send a custom header rather than the followings:
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type, but only if the value is one of:
application/x-www-form-urlencoded
multipart/form-data
text/plain
the type cors request is not "simple" anymore with a custom header, so when the client makes the request in fact it is making a pre-request with method "OPTIONS" first and then makes the "GET".. in between I was getting 404 error.
I added then to my server:
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", 'X-Requested-With, Content-Type, token');
res.header('Access-Control-Allow-Methods', 'GET, POST', 'DELETE', 'PUT', 'OPTIONS');
res.header('Access-Control-Request-Method', 'GET');
res.header('Access-Control-Request-Headers', 'token');
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
// next();
});
It was supposed to work with the access-control headers I added, but it was still sending back the 404 error.. So the work around was to add
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
Because as I said before, with a custom header the client first ask for permissions with OPTIONS method, and the sends the proper GET or whatever.
I did not find out another solution since this seems to be a work around, but at least I am not stuck anymore.
This is a good and practical link a about CORS
http://www.html5rocks.com/en/tutorials/cors/
Hope this helps someone.
King regards
I'm not too versed with CSRF and the likes, but I do believe this might be the issue I had with contacting my Express server with Angular.
http://mircozeiss.com/using-csrf-with-express-and-angular/
As stated in that article, Angular uses it's own X-XSRF-TOKEN for CSRF protection. Hence, you need to take that into account when setting up your server.
Following along with that guide and Express v3 all my requests going from the client side to the server side, magically started working.
If this is not the case (and I'm way out there), let me know.
What does your full serverside config look like?

Resources