问题描述
我是 nodejs 和 Reactjs 的新手。我用 reactjs 和 nodejs 创建了一个示例项目。如果我使用 http://localhost:3000 输入,应用程序工作正常,请求和响应 b/w nodejs 和 reactjs 工作正常。如果我直接用 http://localhost:3000/dashboard 输入,它会直接向浏览器发送响应并显示
{
merchantid: "Not login"
}
在 nodejs 中,我添加了中间件身份验证并将令牌保存在 cookie 中。如果用户直接输入 url http://localhost:3000/dashboard 并且他没有登录,那么我想将他重定向到登录页面。我的问题是我的 reactjs 没有收到响应。
router.get('/dashboard',merchantAuth,async (req,res) => {
try {
if(!req.merchant){
throw new Error(': merchantid: Not login')
}
}
catch (e) {
const errors = errorhandle(e)
res.status(400).send(errors)
}
});
axios
.get('http://localhost:3000/dashboard')
.then((response) => {
console.log('response: ',response)
})
.catch(function (err) {
console.log('err response data: ',err)
const {merchantid} = err.response.data
if (merchantid){
this.props.history.push("/")
}
})
浏览器消息。这个浏览器消息我应该在 react js 和我中收到,基于我将格式化并显示给最终用户的错误。
解决方法
当用户直接输入 /dashboard url 并且他之前没有登录时,通过使用 res.redirect('/') 修复它。