简体   繁体   English

使用 Axios 登录后尝试在 React 中重定向(单独的前端和后端)

[英]Trying to Redirect in React after Login with Axios (Separate Frontend & Backend)

The answer to my question probably already exists, but I've run out of ideas of where/how to check.我的问题的答案可能已经存在,但我已经不知道在哪里/如何检查。

I'm building a project with a teammate split into separate Frontend and Backends.我正在与一个队友一起构建一个项目,该项目分为单独的前端和后端。

After the login form is submitted, I'm able to successfully set an authorization token in localStorage but get an error with trying to redirect the user from the root "/" page to a "/home" page where the main content will be.提交登录表单后,我能够在localStorage中成功设置授权令牌,但尝试将用户从根“/”页面重定向到主要内容所在的“/home”页面时出错。 I don't think <Link to="/home" /> is the right solution, not sure if <Redirect /> is.我不认为<Link to="/home" />是正确的解决方案,不确定<Redirect />是否正确。 I was trying axios.get("/home") but this is the error that I get:我正在尝试axios.get("/home")但这是我得到的错误:

GEThttp://localhost:3000/home
[HTTP/1.1 404 Not Found 5ms]

catch Error: Request failed with status code 404
    createError createError.js:16
    settle settle.js:17
    handleLoad xhr.js:62
    dispatchXhrRequest xhr.js:37
    xhrAdapter xhr.js:13
    dispatchRequest dispatchRequest.js:52
    promise callback*request Axios.js:61
    method Axios.js:76
    wrap bind.js:9
    handleSubmit Login.js:32
    React 14
    unstable_runWithPriority scheduler.development.js:646
    React 4

CODE:代码:

import React, { useState } from "react";
import { BrowserRouter as Router, Redirect } from "react-router-dom";
import axios from "axios";

export default function Login(props) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errorMsg, setErrorMsg] = useState("");

  function handleChange (e) {
    if (e.target.name === "email") {
      setEmail(e.target.value);
    } else {
      setPassword(e.target.value);
    }
  }

  async function handleSubmit (e) {
    e.preventDefault();
    try {
      const res = await axios.post("/api/user/login", { email, password});
      console.log(res);
        if (!res.data.error) {

        localStorage.setItem("authorization", "Bearer: " + res.data); // works
        return await axios.get("/home");
      } else {
        console.log("1st", res.data.error)
      }
  } catch (error) {
    console.log("catch", error);
  }

  }

  return (
    <form onSubmit={ handleSubmit } >
      { errorMsg && <div className="errorMsg">Error: { errorMsg }</div> }
      <label>Email: <input type="email" name="email" value={email} onChange={ handleChange } placeholder="you@email.com" required/></label><br />
      <label>Password: <input type="password" name="password" value={password} onChange={ handleChange } placeholder="********" required/></label>
      <button type="submit" name="button">Submit</button>
    </form>
    )
  }

try to use useHistory from react-router-dom .尝试使用react-router-dom中的useHistory After successfully set token then use history.push('/route-name') to go to your preferred page.成功设置令牌后,然后使用history.push('/route-name')到 go 到您的首选页面。

import {useHistory} from 'react-router-dom';

const history = useHistory();

async function handleSubmit (e) {
    e.preventDefault();
    try {
      const res = await axios.post("/api/user/login", { email, password});
      console.log(res);
        if (!res.data.error) {

        localStorage.setItem("authorization", "Bearer: " + res.data); // works
        history.push("/home");
      } else {
        console.log("1st", res.data.error)
      }
  } catch (error) {
    console.log("catch", error);
  }


I guess you are confused with routing in frontend and routing in backend .我猜你对frontend路由和backend路由感到困惑。 Routing in backend is related with your endpoints: /api/user/login , /api/user and so on.后端路由与您的端点相关: /api/user/login/api/user等等。 Those return data when you make a http call (with axios in your case).当您进行http调用时,那些返回数据(在您的情况下使用axios )。 Routing in frontend is related with the flow between pages (aka navigation).前端的路由与页面之间的流程(又名导航)有关。 So /home is a route in your frontend and react-router-dom has access to it.所以/home是你前端的一个路由, react-router-dom可以访问它。 To be able to jump to new pages, the most straightforward way is to call history.push("/home") using the useHistory() hook (inside your React component) as Zahid showed or accessing history as props if <Login> component is wrapped by a <Route> component为了能够跳转到新页面,最直接的方法是使用useHistory()钩子(在你的 React 组件中)调用history.push("/home") ,就像 Zahid 显示的那样,或者如果<Login>组件访问history作为道具由<Route>组件包裹

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

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