从前端javascript发送POST请求到后端node.js
在前端脚本中,我有这样的代码来创建 POST 请求 到服务器。
var xhr = new XMLHttpRequest();
xhr.open("POST", "/visitor/detect/1", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: "test"
}));
然后这是我在服务器中的路线,
router.post('/visitor/detect/1', (req, res) => {
console.log(req.body);
res.redirect('/visitor/login');
});
我希望在成功发布请求后将页面重定向到 /visitor/login,但事实并非如此。但是,它正在显示 req.body。
这是什么问题,如何才能成功从前端发送post请求并将页面重定向到后端?
In the front-end script, I have a code like this to create the POST request
to the server.
var xhr = new XMLHttpRequest();
xhr.open("POST", "/visitor/detect/1", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: "test"
}));
Then here is my route in my server
router.post('/visitor/detect/1', (req, res) => {
console.log(req.body);
res.redirect('/visitor/login');
});
I'm expecting to redirect the page to /visitor/login after a successful post request, but it didn't. However, it is displaying the req.body.
What is the problem, and what way can I do to successfully send the post request from the front-end and redirect the page to the back-end?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法按照您尝试的方式使用 ajax 请求进行重定向。这是一个片段,我认为您正在尝试做的事情。您还可以查看 fetch api 而不是使用 XMLHttpRequest。
在服务器端:
客户端:
You cannot redirect with the ajax request the way you are trying to do it. Here is an snippet that does what I think you are trying to do. You might also look into the fetch api instead of using XMLHttpRequest.
On the server:
Client side: