【问题标题】:Not able to res.send() server response, but able to console.log the same response with Express无法 res.send() 服务器响应,但能够使用 Express 控制台记录相同的响应
【发布时间】:2020-10-21 01:46:45
【问题描述】:

我正在使用 Express 路由开发自定义集成解决方案,在对 firebase 进行 fetch 调用后,我需要对我的服务器的响应是来自 firebase 的响应,以向我显示来自于的任何问题(例如身份验证错误)在那里。

我一直在尝试使用 res.send() 来显示响应,但它会抛出“TypeError:将循环结构转换为 JSON”错误,但是当 console.logging 相同的响应时,它会给我正确的响应(这是一个身份验证错误)。这有什么关系?

代码如下:

router.route("/bankval").get (fetchAirtabeleRecords, (req, res) => {

    fetch(`https://xxxxxxxxxxxx.firebaseio.com/integratedData.json?auth=${FIREBASESECRET}`,{
    method: 'PUT',
    headers:
    {
        Authorization: 'Bearer ' + FIREBASESECRET,
        'Content-Type': 'application/json'
    },

    body: JSON.stringify({bankValuation: res.bankVal}) // correct values here
})

.then((res) => res.json())

.then(res.send(res)) // This throws me the error

.then((res)=> { console.log('response: ', res); }) // This works and displays expected "error: 'Unauthorized request.' from firebase, but it's only in console, so it's not good enough."


// .then(res.send({bankValuation: res.bankVal}))   // this works, but if authentication error occurs it still displays the correct data, when it's obviously not sent to firebase. Only using this for testing purposes.

.catch(err=> { console.log('error: ',err); }) })

我对此很陌生,所以也许我完全倒退了或其他什么,但感谢任何输入。

谢谢。

【问题讨论】:

    标签: node.js express routes


    【解决方案1】:

    你覆盖了 res,所以试试这个:

    .then((resp) => resp.json())
    
    .then((resp) => res.send(resp))
    
    .then((resp)=> { console.log('response: ', resp); })
    

    【讨论】:

    • 哦,伙计!做到了!!!太感谢了。这么多小时,我试图弄清楚。您能否更详细地简要介绍一下这笔交易的内容?再次感谢。
    • 你有res变量(req, res) => {然后当你写在res下面(res) => res.json()你覆盖自定义res变量有方法send。所以当你执行res.send 你的res 已经只是没有send 方法的JSON
    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2020-07-16
    • 2017-07-29
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多