Response to preflight request doesn't pass access control check with AngularJS - 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?

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();
});

403 forbidden Rest API (node js) in Angular js1

I am calling nodeJS REST API running on different localhost into an angular app,
in postman I get the expected result. but in angular application it is falling due to 403 error, It is happening because of preflight( Response for preflight has invalid HTTP status code 403). I tried to remove some default headers using $httpprovider and also tried to use proper server name instead of wildcard(*) in access-control-allow-region nothing worked.Looking for help!
There is no Authentication for preflight requests.
Posting my req-respo snap
By handling OPTIONS request at server side i am able to solve the problem,
This post solved my problem
By adding following line of code
app.use(function (req,res,next){
if (req.method === 'OPTIONS') {
console.log('!OPTIONS');
var headers = {};
// IE8 does not allow domains to be specified, just the *
// headers["Access-Control-Allow-Origin"] = req.headers.origin;
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
headers["Access-Control-Allow-Credentials"] = false;
headers["Access-Control-Max-Age"] = '86400'; // 24 hours
headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
res.writeHead(200, headers);
res.end();
} else {
//...
other requests
}
});

angular $http request from 80 port to another port

I am trying to hit a node api with port 3000 on local server from a angular 1 project using $http method but I am getting this error:
XMLHttpRequest cannot load http://localhost:3000/login. Request header
field Authorization is not allowed by Access-Control-Allow-Headers in
preflight response.
I also added the Access-Control-Allow-Origin : * in node js as :
req.on('end', function() {
req.rawBody = req.rawBody.toString('utf8');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*');
// 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', false);
next();
});
And my angular code is :
var req = {
method: 'POST',
url: 'http://localhost:3000/login',
headers: {
'Content-Type': 'application/json',
// 'cache-control': 'no-cache'
},
data: { username: username, password: password },
json: true
};
$http(req).then(function successCallback(response){
console.log(response);
}, function errorCallback(response){
console.log("Error : ");
console.log(response);
});
But still I am getting this error.
The error is in the preflight response as specified.
So you need to handle the OPTIONS method :
req.on('end', function() {
req.rawBody = req.rawBody.toString('utf8');
res.setHeader('Access-Control-Allow-Origin', 'http://localhost');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*');
// 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', false);
if (req.method === "OPTIONS") {
return res.status(200).end();
}
return next();
});
This is due to the way browsers handle cross-origin request. An OPTIONS request (preflight) is sent before your POST to get allowed origins, headers and methods.

CORS Issue in Web Console (angular js)

I have a developed a web console in angular JS in which I am using post and put methods and making HTTP requests in which I send json and calling a WSO2 REST API to get response accordingly. Its running on server but I am facing CORS problem. I have add add extension in browser and enable it otherwise I get following error.
XMLHttpRequest cannot load http://127.197.200.100:8000/ManagementAPI/createuser. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.197.200.100:8000' is therefore not allowed access.
This is how I am sending request
CreateUser: function(adata) {
var config = {
headers :{
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
var promise = $http.post(213.187.243.177:8283/ManagementAPI/createuser,adata,config).then(function (response) {
return [response.status,response.data];
},function (response) {
console.log("Error Returned" + response.status);
return [response.status,response.data];
});
return promise;
},
I have tried ThisLink for solution but did not work. Need a solution for accessing it without CORS.
Set headers in back end for avoiding CORS issues .
Sample code in php is shown in below
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}

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

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.');
}
});
});

Resources