$(document).ready(function() {
$('#submitBtn').click(function(e) {
e.preventDefault();
// 准备要发送的JSON数据
var jsonData = {
username: $('#username').val(),
email: $('#email').val(),
action: 'register'
};
// 使用jQuery的ajax方法发送POST请求
$.ajax({
url: '/process-data',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(jsonData),
success: function(response) {
// 服务器返回重定向URL时执行
if (response.redirect) {
window.location.href = response.redirect;
}
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
});
});
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 中间件用于解析JSON请求体
app.use(bodyParser.json());
// 处理POST请求
app.post('/process-data', (req, res) => {
// 获取前端发送的JSON数据
const receivedData = req.body;
console.log('Received data:', receivedData);
// 处理数据逻辑...
// 返回包含重定向URL的JSON响应
res.json({
status: 'success',
message: 'Data processed successfully',
redirect: '/success-page' // 重定向的目标URL
});
});
// 成功页面路由
app.get('/success-page', (req, res) => {
res.send('操作成功!');
});
// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
原因:前端没有正确处理服务器返回的重定向URL 解决:确保服务器返回的JSON中包含正确的redirect字段,前端代码正确解析该字段
原因:前端和后端不在同一个域下 解决:
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
原因:发送的数据不是有效的JSON格式 解决:
JSON.stringify()
转换数据body-parser
中间件如果不想使用jQuery,可以使用原生JavaScript的Fetch API:
document.getElementById('submitBtn').addEventListener('click', function(e) {
e.preventDefault();
const data = {
username: document.getElementById('username').value,
email: document.getElementById('email').value
};
fetch('/process-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
if (data.redirect) {
window.location.href = data.redirect;
}
})
.catch(error => console.error('Error:', error));
});
这种实现方式更加现代化,减少了对外部库的依赖。