【问题标题】:UnhandledPromiseRejectionWarning: Cannot set headers after they are sent to the client(closed)UnhandledPromiseRejectionWarning:在将标头发送到客户端后无法设置标头(已关闭)
【发布时间】:2021-02-13 16:21:33
【问题描述】:

我创建了一个程序,首先我使用 res.status(200).send("some html code") 然后重定向

这里是例子

app.get('/callback',async(req,res)=>{
 res.status(200).send("html code")
 res.redirect('/path/url')

})

错误

Cannot set headers after they are sent to the client

【问题讨论】:

    标签: javascript node.js api server backend


    【解决方案1】:

    tl;dr 完全删除行 res.status(200).send("html code")

    发生了很多混乱:

    • 状态码 200 表示没有重定向,因为重定向将是 301 或 302。
    • 调用send 向框架发出信号“我已经完成了,发送这些东西”。之后您无法修改任何有关响应的内容。发送重定向需要您发送不同的响应。
    • 不禁止在重定向上发送任何类型的内容(例如您提到的 HTML),但这是不寻常的,因为大多数客户端只会按照重定向获取实际内容而几乎忽略响应中的内容.

    简而言之:

    • 如果您想重定向,res.status(200) 毫无意义,因为这无论如何都会改变状态代码。
    • res.send("html code") 本身不是问题,但不寻常,可能会被完全忽略。

    【讨论】:

    • 我想用显示 html 代码重定向,比如当用户来到“/callback”然后用内容不同的 url 重定向是可能的?
    • 可以发送内容,我不确定浏览器是否会真正显示它,但要做到这一点,只需删除status(200) 部分。
    【解决方案2】:
    app.get('/callback',async(req,res)=>{
     res.status(200).send("html code") //Remove this 
     res.redirect('/path/url')
    
    })
    
    app.get('/path/url',async(req,res)=>{
     res.status(200).send("html code") //put here 
    })
    

    【讨论】:

      猜你喜欢
      • 2019-09-28
      • 2020-11-01
      • 2021-10-11
      • 2021-06-18
      • 2022-01-14
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多