我想在Express/Node服务器上模拟404错误。我该怎么做呢?
当前回答
从Express 4.0开始,有一个专门的sendStatus函数:
res.sendStatus(404);
如果您使用的是Express的早期版本,请使用状态函数。
res.status(404).send('Not found');
其他回答
Express 4.x的更新答案
不同于在旧版本的Express中使用res.send(404),新方法是:
res.sendStatus(404);
Express将发送一个非常基本的404响应,并显示“Not Found”文本:
HTTP/1.1 404 Not Found
X-Powered-By: Express
Vary: Origin
Content-Type: text/plain; charset=utf-8
Content-Length: 9
ETag: W/"9-nR6tc+Z4+i9RpwqTOwvwFw"
Date: Fri, 23 Oct 2015 20:08:19 GMT
Connection: keep-alive
Not Found
从Express 4.0开始,有一个专门的sendStatus函数:
res.sendStatus(404);
如果您使用的是Express的早期版本,请使用状态函数。
res.status(404).send('Not found');
你不需要模拟它。我认为res.send的第二个参数是状态码。只需将404传递给该参数。
让我澄清一下:根据expressjs.org上的文档,似乎传递给res.send()的任何数字都将被解释为状态码。所以从技术上讲,你可以:
res.send(404);
编辑:我的错,我说的是res而不是req。它应该在响应时调用
编辑:从Express 4开始,send(status)方法已弃用。如果使用Express 4或更高版本,请使用:res.sendStatus(404)。(感谢@badcc在评论中给出的建议)
根据我将在下面发布的网站,这就是你如何设置你的服务器。他们举的一个例子是:
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
以及它们的路由函数:
function route(handle, pathname, response) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;
这是一种方法。 http://www.nodebeginner.org/
从另一个网站,他们创建一个页面,然后加载它。这可能才是你想要的。
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
http://blog.poweredbyalt.net/?p=81
在Express站点,定义一个NotFound异常,并在你想要404页面或重定向到/404时抛出它:
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
throw new NotFound;
});
app.get('/500', function(req, res){
throw new Error('keyboard cat!');
});
推荐文章
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类
- 访问Handlebars.js每次循环范围之外的变量
- 如何用JavaScript截屏一个div ?
- 如何为其他域设置cookie
- 如何使用npm全局安装一个模块?