Javascript 预检响应具有无效的 HTTP 状态代码 404 angular js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33297190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:55:14  来源:igfitidea点击:

Response for preflight has invalid HTTP status code 404 angular js

javascriptangularjsnode.js

提问by croppio.com

I am trying to prepare a Deleterequest in AngularJSto a nodeJSlocal server:

我正在尝试准备对本地服务器的Delete请求:AngularJSnodeJS

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 nodeJSroute looks like this:

我的nodeJS路线是这样的:

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

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

通过 PostMan 的相同请求有效,但在 Google Chrome 上我得到:

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:

启用 CORS:

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

app.use(allowCrossDomain);

回答by pedromarce

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