如何使用 Express/Node 以编程方式发送 404 响应?

发布于 2024-12-19 19:15:49 字数 51 浏览 2 评论 0原文

我想在我的 Express/Node 服务器上模拟 404 错误。我怎样才能做到这一点?

I want to simulate a 404 error on my Express/Node server. How can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

旧梦荧光笔 2024-12-26 19:15:49

从 Express 4.0 开始,有一个专用的 sendStatus 函数

res.sendStatus(404);

如果您使用的是早期版本的 Express,请使用 状态函数 来代替。

res.status(404).send('Not found');

Since Express 4.0, there's a dedicated sendStatus function:

res.sendStatus(404);

If you're using an earlier version of Express, use the status function instead.

res.status(404).send('Not found');
寻找我们的幸福 2024-12-26 19:15:49

Express 4.x 的更新答案

新方法不是像旧版本的 Express 中那样使用 res.send(404) ,而是:

res.sendStatus(404);

Express 将发送带有“Not Found”文本的非常基本的 404 响应:

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

Updated Answer for Express 4.x

Rather than using res.send(404) as in old versions of Express, the new method is:

res.sendStatus(404);

Express will send a very basic 404 response with "Not Found" text:

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
绮烟 2024-12-26 19:15:49

你不必模拟它。我认为 res.send 的第二个参数是状态代码。只需将 404 传递给该参数即可。

让我澄清一下:根据 expressjs.org 上的文档,似乎任何数字都通过了res.send() 将被解释为状态代码。所以从技术上讲,你可以逃脱:

res.send(404);

编辑:我的错,我的意思是res而不是req。应该在响应上调用它

编辑:从 Express 4 开始,send(status) 方法已被弃用。如果您使用的是 Express 4 或更高版本,请改用:res.sendStatus(404)。 (感谢@badcc 在评论中提供的提示)

You don't have to simulate it. The second argument to res.send I believe is the status code. Just pass 404 to that argument.

Let me clarify that: Per the documentation on expressjs.org it seems as though any number passed to res.send() will be interpreted as the status code. So technically you could get away with:

res.send(404);

Edit: My bad, I meant res instead of req. It should be called on the response

Edit: As of Express 4, the send(status) method has been deprecated. If you're using Express 4 or later, use: res.sendStatus(404) instead. (Thanks @badcc for the tip in the comments)

深巷少女 2024-12-26 19:15:49

根据我将在下面发布的网站,这就是您设置服务器的方式。他们展示的一个例子是这样的:

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

According to the site I'll post below, it's all how you set up your server. One example they show is this:

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;

and their route function:

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;

This is one way.
http://www.nodebeginner.org/

From another site, they create a page and then load it. This might be more of what you're looking for.

fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});
            response.end(data);
        });

http://blog.poweredbyalt.net/?p=81

青衫儰鉨ミ守葔 2024-12-26 19:15:49

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!');
});

From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:

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!');
});
末が日狂欢 2024-12-26 19:15:49

IMO 最好的方法是使用 next() 函数:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

然后错误由错误处理程序处理,并且您可以使用 HTML 很好地设置错误样式。

IMO the nicest way is to use the next() function:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

Then the error is handled by your error handler and you can style the error nicely using HTML.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文