Javascript 如果服务器断开连接,是否可以阻止表单提交?

Javascript 如果服务器断开连接,是否可以阻止表单提交?,javascript,html,node.js,Javascript,Html,Node.js,假设我有一个这样的表单,它被提交到POST路由/example: <form action="/example" method="POST"> <input type="text" name="fname"><br> <input type="text" name="lname"><br> <button type="submit">Send</button> </form> serve

假设我有一个这样的表单,它被提交到POST路由
/example

<form action="/example" method="POST">
  <input type="text" name="fname"><br>
  <input type="text" name="lname"><br>
  <button type="submit">Send</button>
</form>
server.js

const app = require('./app');

app.listen(3000, () => {
    console.log('server is running on port 3000');
});
如果服务器断开连接以防止网站崩溃,Javascript是否提供了防止表单提交的方法


我在网上搜索过,但找不到解决此问题的任何此类解决方案。

您可以这样做,但必须以编程方式完成,而不是通过
action
属性隐式完成。为此,您可以使用Promissions中的
then/catch
,或者使用
async/await
尝试/catch,如下例所示:

<form>
      <input type="text" name="fname" />
      <br />

      <input type="text" name="lname" />
      <br />

      <button type="submit">Send</button>
    </form>

    <script>
      const form = document.querySelector('form');

      form.addEventListener('submit', async (event) => {
        event.preventDefault();

        const elements = event.target;
        const firstName = elements['fname'].value;
        const lastName = elements['lname'].value;
        const dataToSend = { firstName, lastName };

        try {
          const response = await fetch('/example', {
            method: 'POST',
            body: JSON.stringify(dataToSend),
            headers: { 'Content-Type': 'application/json' },
          });
          const data = await response.json();

          console.log('Data returned from the server', data);
        } catch (error) {
          console.log('Uups! Something went wrong', error);
        }
      });
    </script>



发送 const form=document.querySelector('form'); form.addEventListener('submit',异步(事件)=>{ event.preventDefault(); 常量元素=event.target; const firstName=elements['fname'].value; const lastName=elements['lname'].value; const dataToSend={firstName,lastName}; 试一试{ const response=wait fetch(“/example”{ 方法:“POST”, 正文:JSON.stringify(dataToSend), 标题:{'Content-Type':'application/json'}, }); const data=wait response.json(); log('从服务器返回的数据',数据); }捕获(错误){ log('Uups!出现了错误',错误); } });
您可以通过AJAX提交表单,并捕获/处理客户端代码中的各种错误/失败。如果我尝试捕获,服务器断开是否会被视为错误?如果“服务器断开”意味着服务器没有响应,那么我想这会导致某种可识别的错误。这取决于您如何使用AJAX,例如您可能正在使用的客户端库或只是手动使用它。无论您如何使用AJAX,您都可以找到如何处理错误的示例,然后开始测试该特定错误。我是否认为可以在node.js中使用
const firstName=req.body.firstName来访问
firstName
?我似乎在POST路由内的app.js文件中执行
console.log(req.body)
时得到了
{}
即firstName和lastName是
未定义的
。是的,您通过body访问这些变量是正确的。您将需要body解析器中间件。我正在使用
app.use(bodyParser.urlencoded({extended:true}))
但由于某些原因,仍然将其视为未定义:/n这应该可以完成工作,您是否在端点定义之前执行它?我建议为这种情况创建另一个问题。
<form>
      <input type="text" name="fname" />
      <br />

      <input type="text" name="lname" />
      <br />

      <button type="submit">Send</button>
    </form>

    <script>
      const form = document.querySelector('form');

      form.addEventListener('submit', async (event) => {
        event.preventDefault();

        const elements = event.target;
        const firstName = elements['fname'].value;
        const lastName = elements['lname'].value;
        const dataToSend = { firstName, lastName };

        try {
          const response = await fetch('/example', {
            method: 'POST',
            body: JSON.stringify(dataToSend),
            headers: { 'Content-Type': 'application/json' },
          });
          const data = await response.json();

          console.log('Data returned from the server', data);
        } catch (error) {
          console.log('Uups! Something went wrong', error);
        }
      });
    </script>