【发布时间】:2019-05-24 19:08:00
【问题描述】:
以下是我的server.js 代码的 MCVE:
let fs = require('fs');
let http = require('http');
http.createServer((req, res) => {
// Handles GET requests
if(req.method == 'GET') {
let file = req.url == '/' ? './index.html': '/login.html'; // just an example
fs.readFile(file, (err, data) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
}
// Handles POST requests
else {
read(status => {
if(status) {
res.writeHead(302, {
'Location': 'http://localhost:8000/login.html',
'Content-Type': 'text/html'
});
res.end();
console.log('Redirected!');
}
});
}
}).listen(8000);
// In my actual script, the `read` function reads JSON files and sends data,
// so I've used the callback function
let read = callback => fs.readFile( './index.html', (err, data) => callback(true) );
而且,我有两个代码中提到的 HTML 文件。
index.html
<input type="submit" onclick='let xhr = new XMLHttpRequest(); xhr.open("POST", "http://localhost:8000"); xhr.send();'>
我使用内联脚本来最小化我的 MCVE 中的流量。出于开发目的,我将在我的网站上使用外部脚本
login.html
<h1>Login</h1>
现在,当我打开http://localhost 时,index.html 会很好地显示出来。正如您所注意到的,index.html 只是一个按钮。因此,当我单击该按钮时,Ajax 请求被成功触发并且一切正常(没有控制台错误),除了页面不重定向这一事实。我不知道它出了什么问题或还缺少什么。
我是 Node.js 的初学者,在 Nodejs - Redirect url 和 How to redirect user's browser URL to a different page in Nodejs? 中阅读了有关重定向的内容,我进行了很多搜索,但没有得到任何提示。感谢您的宝贵时间!
另外,我知道 express,但我不考虑使用框架,因为它们隐藏了核心概念。
编辑:当我尝试在没有回调概念的情况下进行重定向时,它可以正常工作,正如this video 告诉我们的那样。
【问题讨论】:
-
你在处理POST请求时检查过
status的值吗? -
@Pointy
status变量始终是true预期。 -
你为什么不用快递
-
浏览器不会通过 XHR 请求自动重定向,但您可以让 JavaScript 查找“Location”标头和 302 状态,如果找到,让 JavaScript 重定向到位置标头。
标签: javascript node.js ajax redirect server