【发布时间】:2013-11-26 20:50:45
【问题描述】:
因此,当登录验证失败时,我目前使用 res.send(401) 进行响应。但是我想发送一个文本或 html 的 sn-p 以及错误代码。
我试过了:
res.write('string');
res.send(401);
但抛出错误,我的服务器无法启动。
【问题讨论】:
因此,当登录验证失败时,我目前使用 res.send(401) 进行响应。但是我想发送一个文本或 html 的 sn-p 以及错误代码。
我试过了:
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');
【讨论】:
来自express docs中的例子
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);
说你不能在发送后设置标题。
【讨论】: