我的get路由返回401未经授权的状态码和未定义,但一切都在邮差中工作,所以我假设这是在我的反应中隔离的,而不是我的api的问题。使用承载令牌进行身份验证,如果需要可以提供更多的身份验证代码。使用mern stack
获取客户端API文件中的路由-
export const getOneApplication = (user, applicationId) => {
return axios({
url: `${apiUrl}/application/${applicationId}`,
method: 'GET',
headers: {
Authorization: `Token token=${user.token}`
}
})
}
route from app.js-
<Route
path='/application/:id'
element={
<ShowApplication user={user} msgAlert={msgAlert}/>}
/>
从后端api获取路由-
router.get('/application/:id', requireToken, (req, res, next) => {
// req.params.id will be set based on the `:id` in the route
Application.findById(req.params.id)
.then(handle404)
// if `findById` is succesful, respond with 200 and "application" JSON
.then((application) => res.status(200).json({ application: application.toObject() }))
// if an error occurs, pass it to the handler
.catch(next)
})
最后的答案是我没有将用户传递到组件中的useEffect中,这在运行路由时导致我丢失令牌并获得401状态码
const [application, setApplication] = useState(null)
const {user} = props
const { id } = useParams()
console.log('id in showApplication', id)
// empty dependency array in useEffect to act like component did mount
useEffect(() => {
getOneApplication(user, id)
.then(res => {
console.log('this is the res', res)
setApplication(res.data.application)})
.catch(() => {
console.log('show failed')
})
}, [])