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

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)

  • 值得注意的是,它本身就是`res.status(404);`不会发送响应AFAIK.它需要与某些东西链接,例如`res.status(404).end();`或你的第二个例子,或者它需要跟着例如`res.end();`,`res.send( '找不到');` (16认同)
  • 这也适用于渲染页面:`res.status(404).render('error404')` (6认同)

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在评论中提示)

  • 对于Express 4:"express deprecated res.send(status):使用res.sendStatus(status)代替" (2认同)

Bra*_*rad 41

更新了Express 4.x的答案

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)

  • `res.sendStatus(404)`是正确的.它相当于`res.status(404).send()` (4认同)
  • 我很确定它只是 `res.status(404)` 而不是 `res.sendStatus(404)`。 (2认同)
  • 是的!res.sendStatus(404); `相当于`res.status(404).send('Not Found')` (2认同)

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


ale*_*lex 9

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)