【问题标题】:response.body is returning null and response.data is returning undefined in my react+express appresponse.body 返回 null 并且 response.data 在我的 react+express 应用程序中返回 undefined
【发布时间】:2020-01-30 10:18:28
【问题描述】:

React 中的 App.js

  const url = "http://localhost:3001?address="+this.state.location ;
    fetch(url , {
      mode: 'no-cors' // 'cors' by default
    }).then((response)=>{
        console.log(response.data) //undefined
        console.log(response.body) //null
  })
}

我的节点应用中的 app.js

app.get('/weather' , (req , res)=>{
    if(!req.query.address){
        return res.send({
            error : 'Please, provide an address' // want to get this value in my react app after fetch.
        })
    }
    geoCode(req.query.address , (error , {longitude , latitude , place}={})=>{
        if(error)
        {
            return res.send({
                error // want this value
            })
        }
        getWeather (latitude  ,longitude , (error , {temperature , humidity})=>{
            if(error)
            {
                return res.send({
                   error // want this value
                })
            }
           // want these values
            return res.send({
                temperature ,
                humidity ,
                place
            })


        })
    })

})

我想在我的 react 应用程序中获取从我的节点应用程序发送的错误消息或数据。但是 reponse.data 和 response.body 在我的 react 应用中表现不佳。

【问题讨论】:

  • 错过了这里的天气? const url = "localhost:3001?address="+this.state.location ;
  • 您的回复怎么说?我认为您没有收到任何来自 fetch 的响应
  • 将代码更改为:const url = "http://localhost:3001/weather?address="+this.state.location ; const response = await fetch( url , {mode:'no-cors'}); console.log(response.body); console.log(response.data); 但在控制台中仍然返回 null。
  • 在安慰回复时,它显示:Response{ ​ body: null ​ bodyUsed: false ​ headers: Headers { } ​ ok: false ​ redirected: false ​ status: 0 ​ statusText: "" ​ type: "opaque" ​ url: "" }

标签: node.js reactjs express get fetch


【解决方案1】:

API 调用应该是。

  const url = "http://localhost:3001?address=" + this.state.location;
  fetch(url, {
    mode: 'no-cors'
  })
  .then(res => res.json())
  .then((response) => {
    console.log(response.data)
    console.log(response.body)
  })

请参阅此处了解有关在 react 中获取 API 调用的更多信息 -> fetch api call

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    相关资源
    最近更新 更多