如何将承诺结果转换为json?

How to convert promise result into json?

我正在尝试使用 axios 从外部 API 获取 json 并将其提供给我的前端。当我转到我创建的路线时,我看到 json 就好了。但是,当我通过点击终点将它传递到前端并且我控制日志以查看它是否有效时,我得到了这个:frontend console log of promise

这是我获取外部文件的后端代码API:

app.get('/entertainment', async (req,res) => {

 const respy = await axios.get(process.env.API_URL, {
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}`
    }
  })
  .then((resp) =>  res.send(resp.data))
  .catch(e => console.log(e, "SOME ERROR"))
})

前端部分:

componentDidMount(){
     fetch('http://localhost:8000/entertainment').then((res) => {
       this.setState({
         projectData: res.json()
       })
     }).then(res => {
      console.log(this.state.projectData)
     })
   }

我该如何兑现这个承诺?我以为 .then 或 await 会解决它。

您正在将承诺记录到控制台中。正如您在屏幕截图中看到的那样,承诺正在得到解决。它正在通过以下对象解决:

{
  businesses: [...],
  region: [...],
   total
}

你只是没有用它做任何事情。考虑执行以下操作:

在您的前端向 api 发出请求,并在控制台中记录提取解析的数据

fetch(YOUR_SERVER_URL).then((res) => res.json()).then(data => {
  console.log(data);
});

更改您在编辑中包含的代码:

componentDidMount(){
     fetch('http://localhost:8000/entertainment').then((res) => res.json()).then(data => {
       console.log(data)
       this.setState({
         projectData: data
       })
     })
   }