javascript - API 请求在 ajax 中不起作用,但在 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[]
推荐阅读
- python - 使用 Selenium 获取数据
- javascript - 将 JSON 反序列化为与里面的其他类一起类
- python - 在中继传输系统中使用大于平均 SNR 的链路
- javascript - 页面加载问题后将脚本标记附加到头部
- sqlite - 为什么我得到 sqlite3.Operationalerror: near "channel_id": 我的 sqlite3 代码的语法错误?
- flutter - 在颤动中写长文本时如何制作段落?
- c# - 如何修复 System AggregateException ?在 xamarin
- symfony - 如何为 Symfony 5 中的所有表单类型添加自定义默认选项?
- python-3.x - 如何根据字典内列表中的值对字典进行排序并创建字典
- javascript - javascript在for/in循环中更改类型?