[英]API Request not working in ajax but working in POSTMAN
我试图用AJAX中的一个参数向本地服务器发出发布请求。 当我在邮递员中执行请求时,它似乎工作得很好,但是当我使用AJAX执行该请求时,它将发送两个请求,一个请求为204,另一个请求为404,这看起来很奇怪:
<-- OPTIONS /price/current
api_1 | --> OPTIONS /price/current 204 1ms
api_1 | <-- POST /price/current
api_1 | --> POST /price/current 404 1ms -
实际的AJAX请求如下:
getBtc = async() => {
return await fetch("http://localhost:3001/price/current",{
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify({
'symbol':'eth'
})
})
.then(res => {
console.log(res)
if (res.success) {
this.setState({ priceBTC : res.data[0].price })
}
})
控制台日志使用以下信息指定200响应:
Response {type: "cors", url: "http://localhost:3001/price/btc", redirected: false, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:3001/price/btc"
__proto__: Response
理想情况下,我将获得200的状态码
请尝试以下方法:
.then(res => res.json())
.then(jsonRes => {
console.log(jsonRes)
if (jsonRes.success) {
this.setState({ priceBTC : jsonRes.data[0].price })
}
})
.catch(err => {
alert('Something went wrong')
});
在这里,我们将响应res
转换为json
并从中访问data[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.