Ran*_*lue 168 javascript node.js express
我想在我的Express/Node服务器上模拟404错误.我怎样才能做到这一点?
Dre*_*kes 249
现在,在响应对象上有一个专门的status
功能.在打电话之前把它链接到某处send
.
res.status(404) // HTTP status 404: NotFound
.send('Not found');
Run Code Online (Sandbox Code Playgroud)
ros*_*dia 42
您不必模拟它.res.send
我相信的第二个论点是状态代码.只需将404传递给该参数即可.
让我澄清一点:根据expressjs.org上的文档,似乎传递给任何数字res.send()
将被解释为状态代码.从技术上讲,你可以逃脱:
res.send(404);
Run Code Online (Sandbox Code Playgroud)
编辑:我的坏,我的意思是res
代替req
.应该在响应中调用它
编辑:从Express 4开始,该send(status)
方法已被弃用.如果您使用的是Express 4或更高版本,请使用:res.sendStatus(404)
代替.(感谢@badcc在评论中提示)
Bra*_*rad 41
res.send(404)
新方法不是像在旧版本的Express中那样使用,而是:
res.sendStatus(404);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
cra*_*pty 10
根据我将在下面发布的网站,这就是你设置服务器的方式.他们展示的一个例子是:
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;
Run Code Online (Sandbox Code Playgroud)
和他们的路线功能:
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;
Run Code Online (Sandbox Code Playgroud)
这是一种方式. http://www.nodebeginner.org/
从另一个站点,他们创建一个页面,然后加载它.这可能是您正在寻找的更多内容.
fs.readFile('www/404.html', function(error2, data) {
response.writeHead(404, {'content-type': 'text/html'});
response.end(data);
});
Run Code Online (Sandbox Code Playgroud)
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!');
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
130533 次 |
最近记录: |