簡體   English   中英

發布請求后顯示新的 html 頁面?

[英]Show new html page after post request?

1. 總結問題

首先我想描述一下這個項目應該如何工作。 我想用 html、css、javascript(以及 expressJS 和 nodeJS)建立我自己的小網站。 我還看過一些關於 Rest-API 及其工作原理的教程。 我想創建一個登錄頁面,您應該在其中輸入密碼才能進入“主頁”。 問題是,我正在處理用戶單擊“提交”按鈕后的請求后,密碼框的值將被發送到服務器進行檢查。 執行此操作后,我不知道如何顯示新的 html 頁面以及如何將用戶重定向到新頁面

2. 描述你嘗試過的東西 & 3. 展示一些代碼

我試過兩種不同的東西。 這是我的 server.js 中代碼的開頭:

var app = express();
var server = app.listen(3000);

app.use(express.static('website'));

首先,我想在我的帖子請求中檢查密碼后發送一個文件:

app.post('/all', function(req, res) {
    if(req.body.password != 'example') {
        return
    }
    res.sendFile('index.html');
});

我發現了這個 github 問題,其中用戶有同樣的問題: https://github.com/expressjs/express/issues/692

但是這種方法似乎不適用於后請求。 所以我嘗試了另一件事。 我已經知道, sendFile()在獲取請求中起作用(正如我在 github 問題中提到的那樣),所以我做了這個:

app.get('/all', function(req, res) {
    res.sendFile('index.html');
});

app.post('/register', function(req, res) {
    if(req.body.password != 'example') {
        return
    }

    res.redirect('/all')
});

對於此代碼示例,我使用了以下堆棧溢出頁面: How to redirect to another page after serving a post request in Node.js? 但它也沒有工作。

3.顯示一些代碼:

html 文檔中的腳本:

    function XHTML_POST(path, parms, callback) {
        req = new XMLHttpRequest();
        var ret = false;
        callbackPOST = callback;

        req.open("POST", path, true);

        req.onload = function () {
            if (req.status != 200 && req.status != 1223 && req.status != 0 && req.status != 204) {
                if (req.status == 401) { }
                else { }
            }

            else {
                callbackPOST = callback;
            }
        }

        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        req.setRequestHeader("Cache-Control", "no-cache");
        req.send(parms);
    }

    function postPass() {
        var pass = document.getElementById('pwBox').value; //id of passwordbox
        XHTML_POST('/register', 'password=' + pass, callback)
    }

    function callback() { }

</script>

單擊提交按鈕后,將執行postPass() function。 希望你能理解我的問題以及我想要做什么。 感謝您閱讀。

您可以使用 html forms:

HTML:

    <form method="POST">
        <input type="email" name="youremail" placeholder="Email Address" required>
        <input type="text" name="yourname" placeholder="Name" required>
        <input class="subscribe-button" type="submit" value="Subscribe">
      </form>

NodeJs 服務器:

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, 'login.html'))
})

app.post("/", (req, res) => {
  //Your Password Verification
  if(true){
    res.sendFile(path.join(__dirname, 'index.html'))
  }else{
    res.sendFile(path.join(__dirname, 'login.html'))
  }
})

暫無
暫無

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

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