簡體   English   中英

從回調函數內部使用“純”Node.js重定向

[英]Redirecting using “pure” Node.js from inside a callback function

以下是我的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) );

而且,我在代碼中提到了兩個HTML文件。

index.html

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

我使用內聯腳本來最小化MCVE中的流量。 出於開發目的,我將在我的網站上使用外部腳本

login.html

<h1>Login</h1>

現在,當我打開http://localhostindex.html顯示得很好。 正如您已經注意到index.html只是一個按鈕。 因此,當我單擊該按鈕時,Ajax請求被成功觸發,一切正常(沒有控制台錯誤)除了頁面不重定向這一事實。 我不知道它出了什么問題或者缺少什么。

我是Node.js的初學者,閱讀有關Nodejs中的重定向 - 重定向網址以及如何將用戶的瀏覽器URL重定向到Nodejs中的其他頁面? ,我搜索了很多,但無法得到一個暗示。 謝謝你的時間!

另外,我知道express,但我不考慮使用框架,因為它們隱藏了核心概念。


編輯 :當我嘗試重定向沒有回調概念,然后它工作正常,如該視頻告訴我們。

這不是node.js的問題。 這就是瀏覽器的行為方式。

Ajax(XHR)不會在瀏覽器中觸發重定向。 當瀏覽器實現XHR時,瀏覽器開發人員假設您希望控制頁面刷新行為。 因此,他們確保XHR不會觸發任何默認操作。 所有重定向都將是靜默的,重定向的結果數據將傳遞給您的XHR對象的onreadystatechange回調。

如果您想要重定向來觸發頁面刷新,您可以選擇不使用XHR。 而是提交表單:

<!-- index.html -->
<form action="http://localhost:8000" method="post">
    <input type="submit">
</form>

如果你想使用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);

然后在瀏覽器中處理該響應:

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();'>

但這很難看,幾乎不可能閱讀。 我建議將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()">

在處理節點js Web應用程序時,您應該使用express,除非您對使用建議的當前節點版本有內部了解。

Express很簡單,你的代碼看起來像這樣(並重定向)

app.get('/index.html',function(req,res,next){
   res.redirect('/path/to/redirect/file')
}

鏈接: http//expressjs.com/en/4x/api.html#res.redirect

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM