Warm tip: This article is reproduced from serverfault.com, please click

html-服务器端发布帖子后如何使用客户端JavaScript显示警报?

(html - How to display an alert using client-side JavaScript after a post has happened on the server side?)

发布于 2020-12-27 19:51:43

我对服务器和节点js和js还是很陌生,但我正在尝试构建一个动态网页。在此网页上,我有一个评论表单,人们可以在其中发表评论。我的问题是,在服务器端,此注释表单可以正常工作,但是我正在尝试实现一些客户端js,以便当他们提交表单时,如果发生错误(例如,并非所有字段都已填写)或没有错误发生,网页上会显示警告消息,说明这两种情况均会显示一条适当的消息。我也希望在按下提交按钮并且如果没有错误的情况下将详细信息保存到服务器后清除表单。当前,在将详细信息保存到服务器之前,该表单将重置,因此在服务器中,所有保存的字段均为空白,并且出现此错误:

GET http://127.0.0.1:3000/comment 404 (Not Found)
handleFormSubmit    @   main.js:43 

这是我的代码: Index.html

<html>
    <head>
    </head>
    <body>
        <h1>Comment!</h1>
            <form action='http://localhost:3000/comment' method='POST' id='CommentSection'>
                <div class='form-group'>
                    <label for='username'>username</label>
                    <input class='form-control' name='username'>
                </div>
                <div class='form-group'>
                    <label for='Title'>Info</label>
                    <input class='form-control' name='title' >
                </div>
                <div class='form-group'>
                    <label for='Comment'>Comment</label>
                    <input class='form-control' name='comment' >
                </div>
                <button type='submit' class='btn btn-primary'>Submit</button>
            </form>
        <script src='client.js'></script>
    </body>
</html>

server.js

let AllComments=[];
app.post('/comment', (req, res) => {
    const com = req.body;
    console.log(com);
    AllComments.push(com);
    res.status(201);
});

client.js

async function commentSubmit(event) {
    fetch('http://127.0.0.1:8090/comment');
    alert('success');
    CommentSection.reset();
}
const CommentSection = document.getElementById("CommentSection");
commentForm.addEventListener("submit", commentSubmit);
Questioner
userj
Viewed
0
Sal 2020-12-28 05:58:44

你将需要在.then()方法中添加一个方法调用handleFormSubmit,因此:

fetch('http://127.0.0.1:3000/comment').then(() => {
    alert('comment added');
})

fetch返回一个Promise,并且是一个async方法调用,因此,在你的情况下,调用是alertfetch调用但不一定完成之后触发的.then()触发方法一旦Promise得到解决,因此为了运行代码一旦发生这种情况,你把它存储在.then()方法。

现在,在你的特定用例中,你想要处理成功的呼叫和错误的呼叫。但是还有另外一个考虑因素-你是仅使用失败的呼叫来确定呼叫是否成功,还是服务器的响应可以表示错误?默认情况下,fetch不将响应转换为json(假设你从服务器返回的数据为json.。为此,你需要执行以下操作(假设服务器也返回成功/失败响应:

fetch('http://127.0.0.1:3000/comment').then((res) => {
    return res.json();
}).then((res) => {
    if (res === 'success') {
        alert('comment added');
    } else {
        alert('An error has occurred when trying to add your comment');
    }
}).catch((e) => {
    alert('An error has occurred when trying to add your comment');

})

我本来想念的其他几点,但来自注释线程中的对话:

由于服务器将API作为POST请求公开,因此你需要向请求中添加其他选项fetch,将方法更改为POST,并添加要发送到服务器的数据。为此,你可以添加以下内容:

let options = {
    method: 'POST',
    headers: {
        "Content-Type": "application/json"
    },
    // where data is your form fields
    body: JSON.stringify(data)
}

// Replace '...' with code from above or whatever functionality you 
// need once Promise resolves
fetch('http://127.0.0.1:3000/comment', options).then(...)

有关更多信息fetch,请访问https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

要获取表单数据值,如果没有太多,可以对每个字段尝试一下: let val = document.getElementById('someId').value

最后,表单的当前设置方式,一旦单击“提交”,它将默认刷新。如果要防止这种情况发生,请在fetch调用之前添加event.preventDefault(),在哪里触发(event此情况下EventListener,你当前的方法签名就足够了)。