如何从 xhr 请求重定向 [英] How to redirect from an xhr request

查看:100
本文介绍了如何从 xhr 请求重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我向我的服务器发送一个 xhr 发布请求时.它以 302 重定向回复,但我只能记录整个重定向 html,并且无法让浏览器重定向到新的 url.

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>

登录.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?

提前感谢您的帮助

推荐答案

有没有办法在不做客户端的情况下重定向到'/'?

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

没有.

重定向意味着可以在此处找到您所要求的内容";不是将浏览器导航到此 URL".如果浏览器要导航到它最初请求的 URL,它只会导航到重定向的 URL.

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.

由 XMLHttpRequest 发起的请求会得到一个由 XMLHttpRequest 处理的响应.如果该响应是重定向,则会被跟踪,并且对新请求的响应将由 XMLHttpRequest 处理.

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 是在不离开页面的情况下从 JS 发出 HTTP 请求的行为.

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

如果你想离开页面,不要使用 Ajax.

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

这篇关于如何从 xhr 请求重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆