簡體   English   中英

如何使用 Express/Node 以編程方式發送 404 響應?

[英]How to programmatically send a 404 response with Express/Node?

我想在我的 Express/Node 服務器上模擬 404 錯誤。 我怎樣才能做到這一點?

從 Express 4.0 開始,有一個專用的sendStatus函數

res.sendStatus(404);

如果您使用的是早期版本的 Express,請改用status函數

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

Express 4.x 的更新答案

與舊版 Express 中使用res.send(404)不同,新方法是:

res.sendStatus(404);

Express 將發送一個帶有“未找到”文本的非常基本的 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

你不必模擬它。 我相信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!');
});

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

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

然后錯誤由您的錯誤處理程序處理,您可以使用 HTML 很好地設置錯誤樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM