angular - Http 發送 post 請求 405 方法不被允許
如果這是一個新手問題或使用了不準確的術語,請見諒。因為我是一個新手。
我建立了一個簡單的 Python API 來讀寫資料庫(CSV 檔案),我的前端使用 Angular 5。我成功地從伺服器上的檔案中完整取得資料,但我無法發送資料到它。這裡是問題所在(看起來如此!)
我使用的方法是 POST,而資料是一個 JSON 陣列。
這是關注的程式碼:component.ts 部分:
this._svc.postAPI(this.csvData)
.subscribe(
res => console.log(res),
error => alert('Error!'),
()=> 'Data Submitted to database')
}
services.ts 端:
postAPI(data): Observable<any>{
return this.http.post(this.urlAPI, data);
}
我收到的錯誤是 405 方法不允許,並且控制台的網絡顯示:
一般
Request URL: http://192.168.0.2:5050/api
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: 192.168.0.2:5050
Referrer Policy: no-referrer-when-downgrade
回應標頭
Allow: POST
Content-Length: 23
Content-Type: text/plain; charset=utf-8
Date: Thu, 12 Jul 2018 03:20:39 GMT
Server: Python/3.5 aiohttp/2.3.10
請求標頭
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: 192.168.0.2:5050
Origin: http://evil.com/
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
使用 Postman 一切正常,URL 似乎是正確的,但問題似乎出在資料本身。
我試過這些:
這個沒有用:
postAPI(data): Observable<any>{
return this.http.post(this.urlAPI, '{}');
}
但是這個確實有效:
postAPI(data): Observable<any>{
return this.http.post(this.urlAPI, '[{}]');
}
而這確實有效:
postAPI(data): Observable<any>{
return this.http.post(this.urlAPI, '
[
{
"info": "A",
"dev": "T",
"but": "C",
"msg": "X"
}
]
');
}
我相信我嘗試發佈的數據也正是這個格式,一個 JSON 陣列。
任何協助都將不勝感激。
答案#1
405 表示你的腳本有問題。考慮到其中一個版本可以運作,它不太可能是網頁伺服器的問題。對於這種類型,你需要使用 [] 括號。