【问题标题】:How to send data from NodeJS to React?如何将数据从 NodeJS 发送到 React?
【发布时间】:2019-04-16 04:58:10
【问题描述】:

这是我的代码,它由 Js 文件和 React 文件组成。

//
// JS File 
//
...
app.post('/searchResult',function(req,res)
{
res.send(searchValue);
console.log(`----------------------------`);
console.log(`Search Result :`+ searchValue);
})
...
//
// React File
//
...
axios.post(BASE_URL + '/searchResult')
.then(res => 
{
dataResult = res;
console.log(`The result :`+ dataResult);
})
...
//
//
//

结果:[object Object]

有什么解决办法吗?

【问题讨论】:

  • 在你的 api 中返回 json.... 像这样返回 res.json(searchValue)
  • 在你的 react 应用中,尝试 console.log(res.data)
  • @sathishkumar,我这样放,结果还是[object Object] app.post('/searchResult',function(req,res) { res.send(searchValue); console. log(----------------------------); console.log(Search Result :+ searchValue); res.json(searchValue) })
  • @Israelkusayev 我尝试 console.log(res.data) 但它什么也没显示。这是否意味着它无法传递值?

标签: javascript node.js reactjs axios


【解决方案1】:

当您查看响应时,它包含很多内容以及您从 api 端点作为响应发送的数据,这些数据以嵌套对象格式发送给您。因此,您需要指定要访问响应的哪一部分。 尝试使用以下内容:

dataResult = res.data;
OR
dataResult = res.body;

希望这会有所帮助!

【讨论】:

  • 我尝试了 res.data 和 res.body。两者的结果仍然相同,即 [object Object]
  • 将其包装在 JSON.stringify 中。像这样 JSON.stringify(res.data)
【解决方案2】:

如果您只想获得响应,这应该可行:

    axios.post(BASE_URL + '/searchResult').then(({data}) => {
        console.log(data);
    })

如果您将数据作为字符串返回,请尝试:

const result = JSON.parse(data);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2019-07-07
    • 2019-09-20
    相关资源
    最近更新 更多