MEANスタックでREST APIとクライアント側フレームワークを作成しました。 ローカルで作業した後、私はHerokuでAPIをデプロイしました。PUTメソッドが機能しない(Express&Angular)
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ヘッダを扱っ:CORSが動作する必要があるように私のエクスプレスのルートでは、私はres.headersを扱う
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メソッドの詳細を読み取ろうとしましたが、私はできませんなぜそれが機能していないのか理解してください。誰かが私にこの1つを助けることができますか?
"アクセス制御 - 許可 - メソッド" ヘッダを交換してみてください: "PUT"、あなたのサービスで 、 "Accesの-CONTROL--方法を許可" "GET、PUT、POST、DELETE" としてみてくださいとサーバーのif条件とリターンをコメントします。 –
HI @KethaKavya、ご返信ありがとうございます。私はそれを 'code'に変更しました。res.header(" Acces-Control-Allow-Methods "、" GET、POST、OPTIONS、PUT、DELETE ");サーバ側で 'code'を実行してもエラーが発生しました –
問題は' Acces-Control-Allow-Methods'のtypoです。 – Alexander