首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Express/Node以编程方式发送404响应?

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

Stack Overflow用户
提问于 2011-12-06 07:15:30
回答 5查看 174.4K关注 0票数 213

我想在我的Express/Node服务器上模拟一个404错误。我该怎么做呢?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-05-08 18:49:36

从Express4.0开始,就有了专门的sendStatus function

代码语言:javascript
复制
res.sendStatus(404);

如果您使用的是早期版本的Express,请改用status function

代码语言:javascript
复制
res.status(404).send('Not found');
票数 312
EN

Stack Overflow用户

发布于 2015-10-24 04:09:02

Express 4.x的更新答案

与在旧版本的Express中使用res.send(404)不同,新的方法是:

代码语言:javascript
复制
res.sendStatus(404);

Express将发送一个带有“找不到”文本的非常基本的404响应:

代码语言:javascript
复制
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
票数 55
EN

Stack Overflow用户

发布于 2011-12-06 07:48:36

根据我将在下面发布的网站,这一切都是你如何设置你的服务器。他们展示的一个例子是:

代码语言:javascript
复制
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;

以及它们的路由函数:

代码语言:javascript
复制
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/

从另一个站点,他们创建一个页面,然后加载它。这可能是你想要的更多东西。

代码语言:javascript
复制
fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});
            response.end(data);
        });

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

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8393275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档