Javascript 尝试在使用Axios登录后在React中重定向(前端和后端分开)
我的问题的答案可能已经存在,但我已经不知道在哪里/如何检查了 我正在与一名队友一起构建一个项目,将其分为独立的前端和后端 提交登录表单后,我能够在localStorage中成功设置授权令牌,但在尝试将用户从根/页重定向到主内容所在的/主页时出错。我认为这不是正确的解决方案,不确定是否是。我正在尝试axios.get/home,但这是我遇到的错误:Javascript 尝试在使用Axios登录后在React中重定向(前端和后端分开),javascript,reactjs,axios,Javascript,Reactjs,Axios,我的问题的答案可能已经存在,但我已经不知道在哪里/如何检查了 我正在与一名队友一起构建一个项目,将其分为独立的前端和后端 提交登录表单后,我能够在localStorage中成功设置授权令牌,但在尝试将用户从根/页重定向到主内容所在的/主页时出错。我认为这不是正确的解决方案,不确定是否是。我正在尝试axios.get/home,但这是我遇到的错误: GEThttp://localhost:3000/home [HTTP/1.1 404 Not Found 5ms] catch Error: Re
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
代码:
尝试使用react路由器dom中的useHistory。成功设置令牌后,使用历史记录。按“/route name”转到首选页面
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);
}
我想你会把前端的路由和后端的路由搞混了。后端中的路由与端点:/api/user/login、/api/user等相关。在您的案例中,当您使用axios进行http调用时,这些将返回数据。 前端的路由与页面之间的流(也称为导航)有关。So/home是前端的一条路由,路由器dom可以访问它。为了能够跳转到新页面,最简单的方法是调用history.push/home,如Zahid所示,在React组件中使用useHistory钩子,或者如果组件由组件包装,则作为道具访问历史
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);
}