从评论和帖子“What is the difference between post API call and form submission with post method?”中可以看出,Ajax请求(包括Fetch API)与传统的表单提交在处理重定向时有所不同。
- 传统的表单提交会自动更新浏览器显示并遵循重定向。
- 使用Fetch API等进行的Ajax请求在重定向时并不会自动更改浏览器的显示;它们仅获取重定向的内容。
在一个具有如下结构的Express.js应用程序中:
项目根目录
|
├── node_modules/ [依赖项]
|
├── public/ [静态文件]
| ├── css/ [CSS文件]
| ├── images/ [图片文件]
| └── js/ [JavaScript文件]
| └── formSubmitter.js
| └── login.js [包含AJAX请求和window.location代码]
|
├── views/ [视图模板]
| ├── index.ejs
| └── ...
|
├── app.js [Express应用入口点]
|
└── package.json [项目元数据和依赖项]
AJAX/Fetch API方法
对于Ajax或Fetch API,您需要在JavaScript中手动处理重定向。尽管Fetch API可以自动跟随重定向,但它不会自动更新浏览器的显示或URL。您的JavaScript应该处理最终响应,并在必要时更新window.location
。
在这种情况下,《/js/formSubmitter.js》脚本包含了对重定向的检查并手动处理它:
// 使用Fetch API提交数据并处理重定向的函数
function submitForm(url, data) {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data), // 序列化数据
redirect: 'manual' // 不要自动跟随重定向
})
.then(response => {
if (response.status === 302 || response.status === 301) { // 检查重定向状态
const redirectUrl = response.headers.get('Location');
window.location.href = redirectUrl; // 手动将窗口位置更新为重定向URL
} else {
return response.json(); // 如果没有重定向,则处理响应数据
}
})
.then(data => {
if (data) {
console.log(data); // 记录或处理数据
}
})
.catch(error => console.error('Error:', error));
}
此脚本适用于单页应用程序(SPAs)或需要控制提交过程而不进行全页面刷新的情况。
传统表单提交方法
如果需要执行POST请求后跟随服务器端重定向(例如,在支付网关中),动态创建并提交表单是一种更好的方法。这种方法模拟了传统的表单提交,允许浏览器处理POST请求并自动跟随服务器端重定向。
《formSubmitter.js》用于传统表单提交的脚本:
function submitForm(url, data) {
const form = document.createElement('form');
form.method = 'post';
form.action = url;
// 向表单添加隐藏字段
for (const key in data) {
if (data.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = data[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit(); // 浏览器将跟随服务器端重定向
}
在你的app.js
中,确保提供静态文件服务,以便客户端脚本能够访问:
const express = require('express');
const app = express();
app.use(express.static('public')); // 提供静态文件服务
// 其他Express配置
app.listen(3000, () => console.log('Server is running on port 3000'));
在你的index.ejs
或其他HTML模板中,包含《formSubmitter.js》脚本并在表单提交时使用它:
<!DOCTYPE html>
<html>
<head>
<title>我的网页</title>
<!-- 其他头部元素 -->
</head>
<body>
<h1>欢迎来到我的网页</h1>
<form id="myForm">
<!-- 表单字段 -->
<button type="submit">提交</button>
</form>
<script src="/js/formSubmitter.js"></script>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
const formData = {/* 表单数据收集 */};
submitForm('/api/submit', formData);
});
</script>
</body>
</html>
当表单提交时,submitForm
将动态创建并提交一个表单。浏览器随后会自动跟随任何服务器端的重定向。