如何让node.js服务器在输入无效网址时将用户重定向到404.html页面?
我做了一些搜索,看起来大多数结果都是针对Express,但我想在纯node.js中编写我的服务器.
确定"错误"网址的逻辑特定于您的应用程序.如果您正在使用RESTful应用程序,它可能是一个简单的文件未找到错误或其他内容.一旦你想出来,发送重定向就像这样简单:
response.writeHead(302, { 'Location': 'your/404/path.html' //add other headers here... }); response.end();
可以使用:
res.redirect('your/404/path.html');
要指示缺少文件/资源并提供404页面,您无需重定向.在同一请求中,您必须生成响应,状态代码设置为404,404 HTML页面的内容作为响应正文.以下是在Node.js中演示此示例的示例代码.
var http = require('http'), fs = require('fs'), util = require('util'), url = require('url'); var server = http.createServer(function(req, res) { if(url.parse(req.url).pathname == '/') { res.writeHead(200, {'content-type': 'text/html'}); var rs = fs.createReadStream('index.html'); util.pump(rs, res); } else { res.writeHead(404, {'content-type': 'text/html'}); var rs = fs.createReadStream('404.html'); util.pump(rs, res); } }); server.listen(8080);
res.writeHead(404, {'Content-Type': 'text/plain'}); // <- redirect res.write("Looked everywhere, but couldn't find that page at all!\n"); // <- content! res.end(); // that's all!Redirect to Https
res.writeHead(302, {'Location': 'https://example.com' + req.url}); res.end();
Just consider where you use this (e.g. only for http request), so you don't get endless redirects ;-)
我使用了switch语句,默认为404:
var fs = require("fs"); var http = require("http"); function send404Response (response){ response.writeHead(404, {"Content-Type": "text/html"}); fs.createReadStream("./path/to/404.html").pipe(response); } function onRequest (request, response){ switch (request.url){ case "/page1": //statements break; case "/page2": //statements break; default: //if no 'match' is found send404Response(response); break; } } http.createServer(onRequest).listen(8080);
试试这个:
this.statusCode = 302; this.setHeader('Location', '/url/to/redirect'); this.end();