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



假设我有一个这样的表单,它被提交到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>

app.js:

app.post('/example', (req, res) => {
... 
});

server.js

const app = require('./app');
app.listen(3000, () => {
console.log('server is running on port 3000');
});

如果服务器断开连接以防止网站崩溃,Javascript是否提供了一种防止表单提交的方法?

我在网上搜索过,但找不到任何这样的解决方案。

您可以执行此操作,但必须以编程方式执行,而不是通过action属性隐式执行。为此,您可以使用Promises中的then/catch,或者像下面的示例一样尝试/catch使用async/await

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

最新更新