在客户端浏览器中使用 fetch api,GET 或 POST 没有问题,但 fetch 和 DELETE 有问题。它似乎将 DELETE 请求方法更改为 OPTIONS。
大多数研究表明是一个cors问题,但我已经涵盖了cors问题。
我不确定这是否是 valid fetch spec api link但它显示:
A CORS-safe listed method is a method that is
GET
,HEAD
, orPOST
.
我不确定这是否意味着我不能在使用 cors 获取时使用 DELETE,这就是我遇到问题的原因?
浏览器代码:
var request =
new Request(url, {
credentials: 'include',
mode: 'cors',
method: 'DELETE'
});
return fetch(request)
.then(this.fetchError.bind(this))
.then(this.json)
.then((response)=> {
this.set(`uploadState.${index}.value`, false);
})
.catch((e) => {
console.log(e);
});
},
chrome 网络选项卡:
Request URL:http://72.12.4.3:9000/api/v1/listings/3/47/image-3-47-1492565415145.jpeg
Request Method:OPTIONS
Status Code:401 Unauthorized
Remote Address:72.12.4.3:9000
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:true
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:http://72.12.4.3:8000
Connection:keep-alive
Content-Length:25
Content-Type:application/json; charset=utf-8
Date:Wed, 19 Apr 2017 01:36:07 GMT
ETag:W/"19-9NCRiMyz+z1Bt6fGQfcxA"
X-Powered-By:Express
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:
Access-Control-Request-Method:DELETE
Cache-Control:no-cache
Connection:keep-alive
Host:72.12.4.3:9000
If-None-Match:W/"19-9NCRiMyz+z1Bt6fGQfcxA"
Origin:http://72.12.4.3:8000
Pragma:no-cache
Referer:http://72.12.4.3:8000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
最佳答案
OPTIONS
请求是预期的,基本上是浏览器用来检查请求 DELETE
在这种情况下是否被允许的机制。
OPTIONS
请求似乎从您的服务器获得了 401 Unauthorized
响应。这确实会导致请求失败。改为响应 200 OK
。
顺便说一句,标题 Access-Control-Allow-Headers:
是错误的,但这应该不会影响任何事情。
关于javascript - 使用 DELETE 获取 api 问题 - 即使 cors 良好,也会更改 OPTIONS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485254/