Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

node.js - How to redirect from an xhr request

When I send an xhr post request to my server. It replies with a 302 redirect, but I can only log the entire redirect html, and cannot get the browser to redirect to the new 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 ], () => {
  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>

Is there a way to redirect to '/' without doing it client side?

Thanks in advance for the help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is there a way to redirect to '/' without doing it client side?

No.

A redirect means "What you asked for can be found here" not "Navigate the browser to this URL". The browser will only navigate to the redirected URL if it was going to navigate to the URL it originally asked for.

A request initiated by XMLHttpRequest will get a response that will be processed by XMLHttpRequest. If that response is a redirect, it will be followed and the response to the new request will be handled by XMLHttpRequest.

Ajax is the act of making an HTTP request from JS without leaving the page.

If you want to leave the page, don't use Ajax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...