Reputation: 278
two questions regarding a NextJS/Typescript website I'm making! Currently, I have an authentication function from the front-end, that is then handled on my backend server. As you can see in the code below, this function returns a res.status(400) when there is an error and a res.status(200) when everything works correctly. However, I can't seem to store this status in the responseVariable that awaits for the function to end. Instead, it immediately displays an error on my front-end console. This, however, isn't true when the status is 200; in which case I can actually print out the returned status. So my two questions are:
Authentication function called on front-end:
const handleAuthentication = async () => {
try {
const responseVariable = await axios({
method: 'POST',
url: '/api/auth',
data: {
username: account,
},
})
console.log(responseVariable) //I get here for 200 status, but not 400
} catch (error) {
console.log(error.message)
}
}
Back-end auth handler:
import type { NextApiRequest, NextApiResponse } from 'next'
import { sign } from 'jsonwebtoken'
const Auth = async (req: NextApiRequest, res: NextApiResponse) => {
const { username } = req.body
if (!username) {
res.status(400).json({ message: 'Missing username' })
return
}
const token = sign({ username },process.env.TOKEN_SECRET as string)
return res.status(200).json({ token })
}
}
export default Auth
Upvotes: 1
Views: 573
Reputation: 380
I ran into this exact same issue. Are you using the sentry/nextjs package?
https://github.com/getsentry/sentry-javascript/issues/6670
It was resolved in version 7.30.0
I updated to the latest sentry/nextjs version (7.46.0) and it fixed the issue.
Upvotes: 0
Reputation: 1077
You must use this form for get access to the message that return from api
error.response.data.message
Upvotes: 0