3

I am trying to prepare a Delete request in AngularJS to a nodeJS local server:

this.deleteMusician = function(id) {
        $http({
            url: 'http://localhost:3000/musicians/' + id,
            method: "DELETE",
            data: {}
            //processData: false,
            //headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function (data, status, headers, config) {
            console.log(data);
        }).error(function (data, status, headers, config) {
            console.log(data);
        });
    };

And my nodeJS route looks like this:

app.delete('/musicians/:id', musicians.delete);

The same request via PostMan works, but on Google Chrome i get:

OPTIONS http://localhost:3000/musicians/5628eacaa972a6c5154e4162 404 (Not Found)
XMLHttpRequest cannot load http://localhost:3000/musicians/5628eacaa972a6c5154e4162. Response for preflight has invalid HTTP status code 404

CORS is enabled:

var allowCrossDomain = function(req, res, next) {
  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost');

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

app.use(allowCrossDomain);

Aruna
  • 11,959
  • 3
  • 28
  • 42
croppio.com
  • 1,823
  • 5
  • 28
  • 44
  • Depending upon the middleware used you need to enable CORS on the server infrastructure as this seems to be a cross domain request. – Chandermani Oct 23 '15 at 07:42

1 Answers1

3

You will need to configure your node server to expect options method too.Check this other answer

so:

app.options('/musicians/:id', optionsCB);

and:

exports.optionsCB = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');

  next();
}
Community
  • 1
  • 1
pedromarce
  • 5,651
  • 2
  • 27
  • 27