从前端向后端发出请求的好方法是什么? [节点]

问题描述 投票:0回答:0

“好方法”我的意思是说我应该使用 HTML 表单并设置 action="/post" method="post" 还是使用 JS fetch 来发出请求?

我是 NodeJS 的新手,我想做的是添加一个功能,首先显示要填写的表单,单击提交按钮后它应该保存输入数据库的详细信息,如果成功则显示相同的页面但是而不是显示表单,它应该显示成功部分。 使用 NodeJS、ejs

我尝试执行此功能的方式是从 fontend JS 向后端发出发布请求,然后成功将表单的显示属性更改为

none
并将成功 div 更改为
block
。 但即使在成功将数据保存到数据库后,浏览器仍继续加载(如下图 1 所示)。

image-1:

为什么会这样?

有没有更好的方法来实现这个功能?

服务器端路由器代码:

routes.get("/post", (req, res) => {
    if (req.query.type == "dTP") {
        res.render("post", { dedication: true });
    }
    else if (req.query.type == "sAS") {
        dedication = false;
        res.render("post", { dedication: false });
    }
});

routes.post("/post", (req, res) => {

    console.log("body: " + req.body.postBody);
    const dedicateTo = req.body.dedicateTo;
    const body = req.body.postBody;
    const dedicated = (dedicateTo == undefined) ? false : true;

    const secret = new Secret({
        dedicated: dedicated,
        dedicatedTo: dedicateTo,
        body: body
    });

    secret.save().then((saved) => {
        console.log("saved : " + saved);
        res.json({
            status: 0,
            saved: saved,
            error: null,
        });
        res.end();
    }).catch((err) => {
        res.json({
            status: -1,
            saved: null,
            error: err,
        });
        console.log(err);
        res.end();
        // res.send("<p>Some error occured.</p>");
    });
    // res.redirect("/");

});

客户端JS代码:


var postBtn = document.getElementById("btn-post-secret");
var dedicateTo = document.getElementById("postDedicateTo");
var postBody = document.getElementById("postBody");
var uploadSuccess = document.querySelector(".upload-success");
var divPostForm = document.querySelector(".div-post-form");

postBtn.onclick = () => {
    var dedication;
    var body = postBody.value;

    if (dedicateTo != null) {
        dedication = dedicateTo.value;
    }

    console.log("v: " + dedication);
    console.log("v: " + body);
    postData("http://localhost:3001/post", { dedicateTo: dedication, postBody: body }).then((data) => {
        console.log(data);
        location.href = "/post";
        divPostForm.style.display = "none";
        uploadSuccess.style.display = "block";
        alert("Saved");
    });

}


async function postData(url = "", data) {

    const response = await fetch(url, {
        method: "POST",
        mode: "cors",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
    });
    return response.json();
}


如果有任何更好的方法来实现这个功能,请告诉。

javascript node.js ejs
© www.soinside.com 2019 - 2024. All rights reserved.