使用不带框架或npm模块的纯node.js重定向响应

时间:2019-07-07 18:55:34

标签: node.js

我在不使用框架和npm模块的情况下,在纯node.js上编写了一个简单的应用程序。出现问题-重定向应用程序时,它挂起,几分钟后,浏览器窗口中出现错误:ERR_EMPTY_RESPONSE。 同时,如果在挂断过程中,我快速按ctrl + c然后快速重新启动服务器,该请求将得到满足,并且我将成功重定向到必要的页面。 在php上,类似的过程可以成功进行。

我尝试了许多不同的方法,从将状态从302替换为301,直接写入状态和标题:

response.statusCode = 302;
response.setHeader('Location', url);
response.end();

最后直接添加主机,协议和端口:

url = 'http:localhost:3000/${url}';
response.writeHead (302, {'Location': url});
response.end();
    // Redirect.js Redirect class
    /**
    * Which page will the user be redirected to
    * @param path
    * @param data
    * @return {*}
    */
    to(path, data = {}){
        const session = require('../session').getInstance();

        if(Object.keys(data).length) {
            session.set('redirect', data);
        }

        let url = '/${path.replace(/^\/|\/$/g, '')}/';

        this.response.writeHead(302, {'Location': url});

        this.response.end();
    }
    // php similar code for example
    // helpers.php
    /**
     * @return string
     * http(s)://example.com
     * returns the domain name of the application, including the protocol
     */
     function domain()
     {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $domainName = $_SERVER['HTTP_HOST'];

        return $protocol . $domainName;
     }
     // Redirect.php Redirect class
     /**
     * @param $path
     * @param array $data
     *
     * Which page will the user be redirected to
     */

    public function to($path, $data = [])
    {
       if($data) {
          Session::put('redirect', $data);
       }

       $url = domain() . '/' . trim( parse_url($path, PHP_URL_PATH), '/' );
       header("Location: ${url}");
       exit();
    }

我希望将用户重定向到所需的路由,但结果是应用程序冻结,几分钟后,浏览器窗口中出现错误:ERR_EMPTY_RESPONSE。 但是,如果您快速重新启动服务器,则请求将被执行,并且重定向将成功。

1 个答案:

答案 0 :(得分:0)

注意:这不是答案,而是向OP展示他的Node.js代码策略是正确的(我无法在注释中发布多行代码),而问题的根本原因在于函数to()或代码调用该函数。

问题中显示的Node.js代码策略是正确的。这是一个简单的演示,它使用无框架或npm模块的纯Node.js重定向响应:

var http = require('http');

http.createServer(function (req, res) {
  if (req.url === '/path1') {
    res.statusCode = 302;
    res.setHeader('Location', '/path2')
    res.end();
  } else {
    res.write('Hello Sun!');
    res.end();
  }
}).listen(3000);

HTTP请求GET /path1将被重定向到/path2,并在浏览器中将结果显示为Hello Sun!