【问题标题】:Node JS - load HTML page from fetch APINode JS - 从 fetch API 加载 HTML 页面
【发布时间】:2021-06-19 21:17:48
【问题描述】:

我正在尝试使用 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?");
});

test2.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>

test3.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>

【问题讨论】:

    标签: javascript html node.js


    【解决方案1】:

    这是一个简单的解决方案。 但是做出这样的解决方案有什么意义呢?

    <!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>
    

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 1970-01-01
      • 2021-01-12
      • 2021-09-01
      • 1970-01-01
      相关资源
      最近更新 更多