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

1
  • Depending upon the middleware used you need to enable CORS on the server infrastructure as this seems to be a cross domain request. Commented Oct 23, 2015 at 7:42

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.