从回调函数内部使用"纯"Node.js重定向

rv7*_*rv7 10 javascript ajax redirect node.js server

以下是我的server.js代码的MCVE :

let fs = require('fs');
let http = require('http');

http.createServer((req, res) => {
    // Handles GET requests
    if(req.method == 'GET') {
        let file = req.url == '/' ? './index.html': '/login.html'; // just an example
        fs.readFile(file, (err, data) => {
            res.writeHead(200, {'Content-Type': 'text/html'});
            res.end(data);
        });
    } 

    // Handles POST requests
    else {
        read(status => {
            if(status) {
                res.writeHead(302, {
                    'Location': 'http://localhost:8000/login.html',
                    'Content-Type': 'text/html'
                });
                res.end();
                console.log('Redirected!');
            }
        });
    }
}).listen(8000);

// In my actual script, the `read` function reads JSON files and sends data,
// so I've used the callback function
let read = callback => fs.readFile( './index.html', (err, data) => callback(true) );
Run Code Online (Sandbox Code Playgroud)

而且,我在代码中提到了两个HTML文件.

index.html

<input type="submit" onclick='let xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:8000"); xhr.send();'>
Run Code Online (Sandbox Code Playgroud)

我使用内联脚本来最小化MCVE中的流量.出于开发目的,我将在我的网站上使用外部脚本

login.html

<h1>Login</h1>
Run Code Online (Sandbox Code Playgroud)

现在,当我打开时http://localhost,index.html很好地显示出来.你已经注意到这index.html只是一个按钮.因此,当我单击该按钮时,Ajax请求被成功触发,一切正常(没有控制台错误)除了页面不重定向这一事实.我不知道它出了什么问题或者缺少什么.

我是Node.js的初学者,阅读有关Nodejs中的重定向 - 重定向网址以及如何将用户的浏览器URL重定向到Nodejs中的其他页面?,我搜索了很多,但无法得到一个暗示.谢谢你的时间!

另外,我知道express,但我不考虑使用框架,因为它们隐藏了核心概念.


编辑:当我尝试重定向没有回调概念,然后它工作正常,如该视频告诉我们.

sle*_*man 12

这不是node.js的问题.这就是浏览器的行为方式.

Ajax(XHR)不会在浏览器中触发重定向.当浏览器实现XHR时,浏览器开发人员假设您希望控制页面刷新行为.因此,他们确保XHR不会触发任何默认操作.所有重定向都将是静默的,重定向的结果数据将传递给您的XHR对象的onreadystatechange回调.

如果您想要重定向来触发页面刷新,您可以选择不使用XHR.而是提交表单:

<!-- index.html -->
<form action="http://localhost:8000" method="post">
    <input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

如果你想使用AJAX,你需要像我上面提到的那样在浏览器中进行重定向:

// server.js

// ...

http.createServer((req, res) => {

    // ...

    // Handles POST requests
    else {
        read(status => {
            if(status) {
                res.writeHead(200, {'Content-Type': 'application/json'});
                res.end(JSON.stringify({
                    your_response: 'here'
                }));
            }
        });
    }
}).listen(8000);
Run Code Online (Sandbox Code Playgroud)

然后在浏览器中处理该响应:

index.html

<input type="submit" onclick='let xhr = new XMLHttpRequest();xhr.addEventListener("load", function(){var response = JSON.parse(this.responseText);/* check response if you need it: */if (response.your_response === 'here') {window.location.href = 'http://localhost:8000/login.html';}});xhr.open("POST", "http://localhost:8000");xhr.send();'>
Run Code Online (Sandbox Code Playgroud)

但这很疯狂,几乎不可能阅读.我建议将HTML重构为以下内容:

<!-- index.html -->

<script>
    function handleSubmit () {
      let xhr = new XMLHttpRequest();
      xhr.addEventListener("load", function(){
        var response = JSON.parse(this.responseText);

        /* check response if you need it: */
        if (response.your_response === 'here') {
          window.location.href = 'http://localhost:8000/login.html'; // REDIRECT!!
        }
      });
      xhr.open("POST", "http://localhost:8000");
      xhr.send();
    }
</script>

<input type="submit" onclick="handleSubmit()">
Run Code Online (Sandbox Code Playgroud)

  • @ rv7使用Node.js重定向仅适用于我在上面显示的表单方法.否则,您必须在浏览器中重定向而不是Node.js (3认同)