我正在尝试在 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();
};
应用程序使用(允许跨域);
最佳答案
您还需要将您的 Node 服务器配置为期望选项方法。检查此其他 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();
}
关于javascript - 预检响应具有无效的 HTTP 状态代码 404 angular js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33297190/