我如何发送一个string旁边的错误代码与快递?

所以当一个login无法validation时,我目前respong与res.send(401)。 不过,我想发送一段文字或HTML与错误代码。

我试过这个:

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

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

您将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.status(404).send('Sorry, we cannot find that!'); res.status(500).send({ error: 'something blew up' }); 

一个更详细的例子,但是,即使你尝试渲染模板的作品:

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

要么

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

 res.send(error_code,msg); 

已弃用。 你应该这样做。

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

更新:对于Express v 4.13.4,当你这样做的时候会抛出错误。

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

说他们发送后不能设置标题。