【发布时间】: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