Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用Express/Node以编程方式发送404响应?_Javascript_Node.js_Express - Fatal编程技术网

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

Javascript 如何使用Express/Node以编程方式发送404响应?,javascript,node.js,express,Javascript,Node.js,Express,我想在Express/Node服务器上模拟404错误。我该怎么做呢?你不必模拟它。res.send的第二个参数是状态码。把404传给那个论点 让我澄清一下:似乎传递给res.send()的任何数字都将被解释为状态代码。所以从技术上讲,你可以逃脱: res.send(404); 编辑:我的错,我的意思是res而不是req。应该在响应时调用它 编辑:从Express 4开始,send(status)方法已被弃用。如果您使用的是Express 4或更高版本,请改用:res.sendStatus(40

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

你不必模拟它。
res.send
的第二个参数是状态码。把404传给那个论点

让我澄清一下:似乎传递给
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;
router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}
这是一种方式。

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

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

在中,定义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!');
});

自Express 4.0以来,有一个专门的:

res.sendStatus(404);

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

res.status(404).send('notfound');
Express 4.x的更新答案 与在旧版本的Express中使用res.send(404)不同,新方法是:

res.sendStatus(404);
Express将发送带有“未找到”文本的非常基本的404响应:


我认为最好的方法是使用
next()
函数:

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;
router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

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

模拟的错误与真实的错误有何不同?您也可以使用404:
res.send(404,“找不到ID”+ID)
直接发送状态代码在4.x中不受欢迎,可能会在某个时候被删除。对于Express 4,最好坚持使用
.status(404).send('Not found')
:“Express弃用的res.send(status):改用res.sendStatus(status)”此示例代码不再位于您引用的链接中。这可能适用于早期版本的express吗?它实际上仍然适用于现有代码,您所要做的就是使用错误处理中间件来捕获错误。例如:
app.use(函数(err,res,res,next){if(err.message.indexOf('NotFound')!=-1){res.status(400).send('NotFound dude');};/*else..etc*/})这也适用于呈现页面:
res.status(404)。呈现('error404')
值得注意的是,它本身就是
res.status(404)不会立即发送响应。它需要或者与某个东西链接,例如
res.status(404.end()
或您的第二个示例,或者后面需要加上例如
res.end()
res.send('notfound')
@UpTheCreek,我将从代码中删除第一个示例,以避免出现这种混淆。较短的版本
res.sendStatus(404)
@bentesha计划简单。我很确定它只是
res.status(404)
而不是
res.sendStatus(404)
res.sendStatus(404)
是正确的。它相当于
res.status(404).send()
yesp
res.sendStatus(404)
相当于
res.status(404).send('Not Found')
@JakeWilson现在是什么?是的,我同意,在node/express上下文中使用中间件要一致得多。