【问题标题】:Nodejs - Redirect urlNodejs - 重定向网址
【发布时间】:2011-05-03 00:18:54
【问题描述】:

当用户输入无效的 url 时,如何让 node.js 服务器将用户重定向到 404.html 页面?

我做了一些搜索,看起来大多数结果都是针对 Express 的,但我想用纯 node.js 编写我的服务器。

【问题讨论】:

  • 我曾经认为我的应用在纯 node.js 中会更好,但在安装 express 后非常高兴。我现在无法想象没有 express 的节点 SPA/RESTful Web 服务架构。

标签: node.js redirect


【解决方案1】:

确定“错误”网址的逻辑特定于您的应用程序。如果您正在做一个 RESTful 应用程序,它可能是一个简单的文件未找到错误或其他问题。一旦你弄清楚了,发送重定向就像这样简单:

response.writeHead(302, {
  'Location': 'your/404/path.html'
  //add other headers here...
});
response.end();

【讨论】:

  • 它没有显示我的 404 html 页面,可能只是显示标题。
  • @Magic 不正确。试试Location: /,它会将你重定向到根文件夹。
  • 同意阿瓦尔。我正在使用'Location': '/path/to/my/servers/content'
  • 谢谢。我正在运行一个静态服务器,并以某种方式安装了没有管理员权限的 Node。我在 PC 上没有管理员权限,因此无法更改设置。无论如何,我设法在没有 NPM 或除默认包之外的任何东西的情况下安装了 Node.js,所以我一直在努力使用 vanilla Node.js 完成所有工作。您的技术让我在我的私有 IP 上设置了一个动态端口 80 转发脚本,以将所有端口 80 HTTP 请求重定向到我正在处理的项目的任何端口。谢谢你。现在,我只是为了好玩而考虑将它们转发到端口 80。 ?
【解决方案2】:

要指示丢失的文件/资源​​并提供 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);

【讨论】:

    【解决方案3】:

    如果您使用的是 ExpressJS,则可以使用:

    res.redirect('your/404/path.html');
    

    【讨论】:

    • 仅限快递。不在本机 node.js 应用程序中。
    • @TarunG 感谢您的评论,如果您查看问题的编辑历史记录,您会发现这并不总是那么清楚。
    • 在我的例子中 res.redirect('/login') 只是在 ajax 调用的响应中发送 login.html 内容。如何打开页面?
    • 旧帖子,但也许您正在寻找类似 res.direct('localhost:5000/login') 的东西,特别是如果您在与前端不同的端口上运行您的快速服务器,就像我碰巧一样.
    【解决方案4】:

    404 与内容/正文

    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!
    

    重定向到 Https

    res.writeHead(302, {'Location': 'https://example.com' + req.url});
    res.end();
    

    只需考虑在哪里您使用它(例如,仅用于 http 请求),因此您不会得到无休止的重定向 ;-)

    【讨论】:

      【解决方案5】:

      试试这个:

      this.statusCode = 302;
      this.setHeader('Location', '/url/to/redirect');
      this.end();
      

      【讨论】:

      • 这可能是 Express 代码 sn-p OP 要求纯 node.js 代码
      • 不是 Express 代码。除了this 部分外,这看起来像普通的节点代码。在 NodeJS 中,您编写一个接受两个参数 (request, response) 的处理程序,并且答案中的所有这些调用都在 response 对象上。
      【解决方案6】:

      我使用了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);
      

      【讨论】:

        【解决方案7】:

        您必须使用以下代码:

        response.writeHead(302 , {
                   'Location' : '/view/index.html' // This is your url which you want
                });
        response.end();
        

        【讨论】:

          【解决方案8】:

          使用以下代码在 Native Nodejs 中可以正常工作

          http.createServer(function (req, res) {
          var q = url.parse(req.url, true);
          if (q.pathname === '/') {
            //Home page code
          } else if (q.pathname === '/redirect-to-google') {
            res.writeHead(301, { "Location": "http://google.com/" });
            return res.end();
          } else if (q.pathname === '/redirect-to-interal-page') {
            res.writeHead(301, { "Location": "/path/within/site" });
            return res.end();
          } else {
              //404 page code
          }
          res.end();
          }).listen(8080);
          

          【讨论】:

            猜你喜欢
            • 2011-09-08
            • 2010-11-29
            • 1970-01-01
            • 2014-06-08
            • 2017-10-21
            • 2010-12-31
            相关资源
            最近更新 更多