【发布时间】:2017-03-08 14:40:38
【问题描述】:
我使用 MEAN Stack 制作了一个 REST Api 和一个客户端框架。 在本地工作后,我在 Heroku 上部署了 API。在我的 Express 路线中,我处理 res.headers 以便 CORS 可以正常工作:
app.use('*', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if(req.method === "OPTIONS") {
res.header("Acces-Control-Allow-Methods", "GET, PUT, POST, DELETE");
return res.status(200).json({});
}
next();
});
在客户端我处理了请求头:
app.factory('dataServices', function($http) {
return {
//Get the location information from API
getAll: function() {
return $http({
method: 'GET',
url: url
})
},
get: function(id) {
return $http({
method: 'GET',
url: url + '/' + id
})
},
post: function(id) {
return $http({
method: "POST",
url: url,
data: {}
})
},
put: function(id, data) {
return $http({
method: "PUT",
url: url + '/' + id,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
"Access-Control-Allow-Method": "PUT",
"Content-Type": "application/json charset=UTF-8"
},
data: data
})
},
当我触发 GET 或 POST 请求时没有问题。但是当我尝试触发 PUT 或 DELETE 方法时:
$scope.saveLocation = function(id) {
console.log(id)
dataServices.put(id).then(function successCallback(repsonse) {
$scope.customer = response.data;
})
};
我在控制台中收到以下错误:
XMLHttpRequest cannot load https://bbsalesapi.herokuapp.com/locations/580fd2a672e68a000352783a. Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.
我尝试阅读有关不同 http 方法的更多信息,但我不知道为什么它不起作用。有人可以帮我这个吗?
【问题讨论】:
-
尝试将服务中的标题“Access-Control-Allow-Method”:“PUT”替换为“Acces-Control-Allow-Methods”、“GET、PUT、POST、DELETE”和尝试在您的服务器中评论 if 条件和返回。
-
嗨@KethaKavya,谢谢您的回复。我将其更改为:
coderes.header("Acces-Control-Allow-Methods", 'GET, POST, OPTIONS, PUT, DELETE');code在服务器端但仍然出现错误 -
问题是
Acces-Control-Allow-Methods中的拼写错误。
标签: angularjs node.js rest express cors