newCodeman
newCodeman

Reputation: 1

What's wrong with my get route? I'm receiving a 401 status code when I try to run my get route

my get route is returning a 401 unauthorized status code and undefined but everything works in postman so I'm assuming that this is isolated in my react and not a problem with my api. Using a bearer token for auth and can provide more of the auth code if needed. using mern stack

get route in the api file of my client-

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}/>}
/>

get route from backend 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)
})

Upvotes: 0

Views: 332

Answers (1)

newCodeman
newCodeman

Reputation: 1

The answer ended up being that I was not passing the user into the useEffect in the component, which when running the route caused me to lose the token and get the 401 status code

    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')
            })
    }, [])

Upvotes: 0

Related Questions