简体   繁体   English

res.redirect 在使用 React 时不起作用

[英]res.redirect not workig when working with React

I am using react as frontend and made api using express I have the following code I have stored jwt token in the cookies while logging in for the first then when trying to login in again I check if there is already a token in the cookies if there is token in the cookie (currently I am not verifying it I just want it to work) redirect the user to profile page but it doesn't work.我正在使用 react 作为前端并使用 express 制作 api 我有以下代码 我在第一次登录时将 jwt 令牌存储在 cookie 中然后当尝试再次登录时我检查 cookie 中是否已经有令牌如果有是 cookie 中的标记(目前我没有验证它,我只是想让它工作)将用户重定向到个人资料页面,但它不起作用。 Although an XMLHttpRequest can be seen in the network tab ( click for screenshot ) but it doesn't work.虽然在网络选项卡中可以看到 XMLHttpRequest(单击以获取屏幕截图),但它不起作用。 PS - I am using Axios in the frontend to make a get request. PS - 我在前端使用 Axios 来发出获取请求。

loginRouter.get("/", async (req, res) => {
  try {
    const cookieFound = req.cookies["login-token"];
    if (cookieFound) {
      res.redirect("profile");
    } else {
      res.redirect("login");
    }
    
  } catch (error) {
    console.log(error);
    res.status(500).json("Ooops something went wrong!");
  }
});

code to make a get request in the frontend在前端发出获取请求的代码

useEffect(() => {
    Axios.get("/login");
  }, []);

EDIT:-编辑:-

Backend后端

 loginRouter.get("/", async (req, res) => {
  try {
    const cookieFound = req.cookies["login-token"];
    if (cookieFound) {
      res.send("/profile");
    }
    // res.status(200).json(cookieFound);
  } catch (error) {
    console.log(error);
    res.status(500).json("Ooops something went wrong!");
  }
});

Client客户

    useEffect(() => {
    const alreadyLoggedIn = async () => {
      const url = await Axios.get("/login");

      window.location = url.data;
    };
    alreadyLoggedIn();
  }, []);

To what you have entered I think you should change window.location = url.data to window.location = window.location.hostname + url.data;对于您输入的内容,我认为您应该将window.location = url.data更改为window.location = window.location.hostname + url.data; In your current setup the total url will be set to /profile while you want yourwebsite.com/profile在您当前的设置中,当您想要yourwebsite.com/profile时,总 url 将设置为/profile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM