【问题标题】:Response for preflight has invalid HTTP status code 404 angular js预检响应具有无效的 HTTP 状态代码 404 angular js
【发布时间】:2016-01-22 16:27:57
【问题描述】:

我正在尝试将AngularJS 中的Delete 请求准备到nodeJS 本地服务器:

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

而我的nodeJS 路线看起来像这样:

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

通过 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 已启用:

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

【问题讨论】:

  • 根据所使用的中间件,您需要在服务器基础架构上启用 CORS,因为这似乎是一个跨域请求。

标签: javascript angularjs node.js


【解决方案1】:

您还需要将节点服务器配置为期望选项方法。检查其他answer

所以:

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

和:

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

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2018-04-25
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2023-04-10
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多