Node.js 如何从xhr请求重定向
当我向服务器发送xhr post请求时。它的回复是302重定向,但我只能记录整个重定向html,无法让浏览器重定向到新的url server.jsNode.js 如何从xhr请求重定向,node.js,redirect,xmlhttprequest,hapijs,Node.js,Redirect,Xmlhttprequest,Hapijs,当我向服务器发送xhr post请求时。它的回复是302重定向,但我只能记录整个重定向html,无法让浏览器重定向到新的url server.js const Hapi = require('hapi'); const Inert = require('inert'); const server = new Hapi.Server(); const port = 8888; server.connection({ port }); server.register([ Inert ], ()
const Hapi = require('hapi');
const Inert = require('inert');
const server = new Hapi.Server();
const port = 8888;
server.connection({ port });
server.register([ Inert ], () => {
server.route([
{
method: 'get',
path: '/',
handler: (request, reply) => {
reply.file('index.html');
}
},
{
method: 'get',
path: '/login',
handler: (request, reply) => {
reply.file('login.html');
}
},
{
method: 'post',
path: '/login',
handler: (request, reply) => {
reply.redirect('/');
}
}
]);
server.start(() => {
console.log('Server running on ', server.info.uri);
});
});
index.html
<!doctype html>
<html>
<body>
<h1> Home </h1>
<a href="/login"> go to login </a>
</body>
</html>
家
login.html
<!doctype html>
<html>
<body>
<button id="home">home</button>
<script>
function goHome () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log('Response: ', xhr.response);
}
}
xhr.open('post', '/login');
xhr.send();
}
document.getElementById('home').addEventListener('click', goHome);
</script>
</body>
</html>
家
函数goHome(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=函数(){
如果(xhr.readyState==4&&xhr.status==200){
log('Response:',xhr.Response);
}
}
xhr.open('post','/login');
xhr.send();
}
document.getElementById('home')。addEventListener('click',goHome);
是否有一种方法可以重定向到“/”而不在客户端执行此操作
提前谢谢你的帮助
是否有一种方法可以重定向到“/”而不在客户端执行此操作
没有
重定向的意思是“可以在此处找到您请求的内容”,而不是“将浏览器导航到此URL”。如果浏览器要导航到最初请求的URL,则它将只导航到重定向的URL
XMLHttpRequest发起的请求将得到一个响应,该响应将由XMLHttpRequest处理。如果该响应是一个重定向,那么它将被跟踪,对新请求的响应将由XMLHttpRequest处理
Ajax是从JS发出HTTP请求而不离开页面的行为
如果您想离开页面,不要使用Ajax