Reputation: 658
So first I have my angular app:
var app = angular.module('app', []);
angular.module('app.controllers', []);
app.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
And here is an angular controller:
angular.module('app').controller('loginController', ['$scope', '$http', function($scope, $http){
$http({
method: 'POST',
url: 'https://xxx-xxx.c9users.io:xxxx/api/registerUser',
headers: { 'Content-Type': 'application/json' },
data: { test: 'something' }
});
}]);
And then there's my nodejs code:
var express = require('express');
var app = express();
var bodyParser= require('body-parser');
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");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
app.use(bodyParser.json());
var server = app.listen(process.env.PORT, function () {
var host = server.address().address
var port = server.address().port
});
app.post('/api/registerUser', function (req, res) {
//req.body.test do something..
});
So whenever I try to send this request to the node server. I get the following error in my browser console:
*OPTIONS https://xxx-xxx.c9users.io:xxx/api/registerUser *
XMLHttpRequest cannot load https://xxx-xxx.c9users.io:xxxx/api/registerUser. Response for preflight has invalid HTTP status code 404
And the server never gets the request. BUT, if I just call it like this:
$http.post('https://xxx-xxx.c9users.io:xxxx/api/registerUser');
The server wont have any trouble receiving the request, but there's no data though. What am I doing wrong here?
Upvotes: 1
Views: 1509
Reputation: 723
If you are requesting from other domain you must allow Cross Origin Resources from the server side.
Here is the small node snippet of how to turn on CORS using express framework.
NodeJS Code Snippet
allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
if ('OPTIONS' === req.method) {
res.send(200);
} else {
next();
}
};
app.use(allowCrossDomain);
Upvotes: 3
Reputation: 119
I agree, it seems to me you are missing the options method. Adding this also:
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Upvotes: 0