Simon Sondrup Kristensen Simon Sondrup Kristensen - 1 year ago 71
AngularJS Question

send https request from angular to nodejs. Can't send any data

So first I have my angular app:

var app = angular.module('app', []);
angular.module('app.controllers', []);

delete $httpProvider.defaults.headers.common['X-Requested-With'];

$httpProvider.defaults.headers.common = {};
$ = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};

And here is an angular controller:

angular.module('app').controller('loginController', ['$scope', '$http', function($scope, $http){

method: 'POST',
url: '',
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");


var server = app.listen(process.env.PORT, function () {
var host = server.address().address
var port = server.address().port
});'/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:


XMLHttpRequest cannot load Response for preflight has invalid HTTP status code 404

And the server never gets the request. BUT, if I just call it like this:


The server wont have any trouble receiving the request, but there's no data though. What am I doing wrong here?

Answer Source

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) {
  } else {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download