[英]Can't get the PUT method working (Express & Angular)
我已經使用MEAN Stack制作了REST Api和客戶端框架。 在本地工作后,我在Heroku上部署了API。 在我的Express路線中,我處理res.header,以便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();
});
在客戶端,我處理了req標頭:
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方法的信息,但我不知道為什么它不起作用。 有人可以幫我嗎?
我通常將CORS內容放入中間件,廣告對我有用...:
// middleware
var handleCORS = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
// ...
app.configure(function() {
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: 'my super secret' }));
app.use(express.methodOverride());
app.use(handleCORS);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
使用cors
庫,它將解決問題npm install cors --save
var cors = require('cors');
app.use(cors())
對於PUT請求,必須設置Content-Length標頭。
您的內容類型也有問題,您忘記了;
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",
"Content-Length": Buffer.byteLength(data)
},
data: data
})
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.