angular $http request from 80 port to another port - angularjs

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.

Related

How to send both data and header to a server?

I want to send a header to a server using http call POST request.
When I send the header only, everything is ok.
but when I add some data to the call, I get an error:
http://localhost:3000/test_post.
Request header field Content-Type is not
allowed by Access-Control-Allow-Headers in preflight response.
I use node.js as the server side language, this is the code for the CORS settings:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Expose-Headers", "x-auth");
res.header("Access-Control-Allow-Headers", "x-auth");
next();
});
This is the $http call with angular:
$http({
method: 'POST',
data: {name: 'Dani'},
url: 'http://localhost:3000/test_post'
headers: {
'x-auth': 'some token'
}
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log('error');
});
I know problem is about the CORS, but I don't know what to modify there,
If I remove res.header("Access-Control-Allow-Headers", "x-auth"); from the CORS I can get the data on the server but not the Header.
How can I get them both?
Hope you can help me with that, Thank you.

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

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

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?

angular POST request not working but GET working fine

I know this has been asked, but I tried a lot of things and could not make this work.
I am making GET and POST request from my angular application to laravel backend api's. I am able to fetch json from get request but my POST request fails for json data type. It works for
x-www-form-urlencoded
but I am unable to extract data as it is in json format.
$http.get('http://api.app.mywebsite.com/users').success(function(data){
$scope.user = data;
});
$scope.addUser = function(user){
console.log($scope.user);
$http({
method: 'POST',
url: 'http://api.app.mywebsite.com/users',
dataType: 'json',
data: $scope.user,
headers: {'Content-Type': 'application/json; charset=utf-8' }
}).then(function(result){
console.log(result);
}, function(error){
console.log(error);
})
}
$scope.user is posted on form submit.
The error I get :-
XMLHttpRequest cannot load http://api.app.mywebsite.com/users.
Response to preflight request doesn't pass access control check:
No 'Access-Control- Allow-Origin' header is present on the
requested resource. Origin 'http://app.mybackend.com' is therefore not allowed access.
My CORS.php middleware in laravel :-
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin, X-Requested-With, Accept'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return \Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
return $next($request);
}
routes.php
Route::group(['middleware' => 'cors'], function()
{
Route::resource('users', 'UserController');
});
Update:
http://let-aurn.github.io/laravel-5-cors/
You need to configure your http server to allow cors
Similar question:
How to enable CORS in AngularJs
And:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Resources