簡體   English   中英

Node JS - 從 fetch API 加載 HTML 頁面

[英]Node JS - load HTML page from fetch API

我正在嘗試使用 fetch API 將數據從前端發送到我的 nodeJS 后端服務器。 后端然后返回一個網頁(呈現一個視圖),我在獲取后使用 .then() 捕獲它。

收到后如何加載html頁面(來自nodeJS后端的響應)? 經過一番研究,我發現一種方法是使用 .text(),但它似乎並沒有為我加載新頁面。

路由器文件 (JS)

router.get("/testPost", (req, res) => {
    res.render("test2");
});

router.post("/testPost", (req, res) => {
    console.log(req.body);
    res.render("test3");
    console.log("rendered?");
});

測試2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <script>
        function runCode() {
            weight = true
            data = { weight }
            fetch("/input/testPost", {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            }).then((res) => {
                console.log(res)
                res.text();
            });
        }
    </script>
</head>
<body>
    <button onclick="runCode()">Click me</button>
</body>
</html>

測試3.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Loaded</title>
</head>
<body>
    Page loaded
</body>
</html>

這是一個簡單的解決方案。 但是制定這樣的解決方案有什么意義呢?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test</title>
    <script>
        function runCode() {
            weight = true
            data = { weight }
            fetch("/input/testPost", {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
            .then((res) => res.text())
            .then((res) => {
                const div = document.createElement('div');
                div.innerHTML = res;

                document.body.appendChild(div);

                // if needed full page update
                document.body.innerHTML = res;
            });
        }
    </script>
</head>
<body>
<button onclick="runCode()">Click me</button>
</body>
</html>

暫無
暫無

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

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