首页 > 解决方案 > 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

标签: javascriptajaxreactjshttp-status-code-404http-status-code-204

解决方案


请试试这个:

.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[]


推荐阅读