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:
- Why can't I access the responseVariable when it is a status 400 response?
- I understand I can catch the error instead of looking at the responseVariable, but I can't seem to access the "Missing username" message that should be within the error. Logging error.message returns "Request failed with status code 400"; any way to access the custom message within the JSON? Edit: When I try logging error.response.message, I get the error: "Property 'response' does not exist on type 'Error'."
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