【问题标题】:How do I send a string alongside an error code with express?如何使用 express 将字符串与错误代码一起发送?
【发布时间】:2013-11-26 20:50:45
【问题描述】:

因此,当登录验证失败时,我目前使用 res.send(401) 进行响应。但是我想发送一个文本或 html 的 sn-p 以及错误代码。

我试过了:

res.write('string');
res.send(401);

但抛出错误,我的服务器无法启动。

【问题讨论】:

    标签: node.js http express


    【解决方案1】:

    您将 Express 方法与本机 HTTP 方法混合使用。由于 Express' 在内部使用原生 HTTP 模块,因此您应该使用其中一个。

    // Express
    res.status(401);
    res.send('string');
    // or the shortcut method
    res.send(401, 'string');
    
    // HTTP
    res.writeHead(401);
    res.end('string');
    

    【讨论】:

    • 表示不推荐使用 res.send(status, body):改用 res.status(status).send(body)
    【解决方案2】:

    来自express docs中的例子

    res.status(404).send('Sorry, we cannot find that!');
    res.status(500).send({ error: 'something blew up' });
    

    【讨论】:

      【解决方案3】:

      一个更冗长的例子,但即使你尝试渲染模板也可以:

      res.status(401).send('Unauthorized')

      res.status(401).render('/401.html')

      【讨论】:

        【解决方案4】:
        res.send(error_code,msg);
        

        已弃用。你应该这样做。

        res.status(error_code).send(msg);
        

        更新: 对于 express v 4.13.4,执行此操作时会引发错误。

        res.status(error_code).send(msg);
        

        说你不能在发送后设置标题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多