I couldn't find similar questions so I had to ask this one. I think it's a pretty simple task but I can't figure out how to do it. I'm working with Strapi and Next.js to build an authentication system.
How can the client get the user data back from the server?
// login.js
const handleLogin = (e) => {
e.preventDefault()
axios.post("/api/login", {
identifier: `${credentials.email}`,
password: `${credentials.password}`,
remember: stayLoggedIn,
})
.then(()=> {
// response.data.user
Router.push("/")
}).catch(error => {
console.log("Error reaching /api/login ->", error)
})
}
The client needs to get response.data.user
back from the server.
// /api/login.js
export default (req, res) => {
const {identifier, password} = req.body;
// Strapi login
axios.post(`${API_URL}/api/auth/local`, {
identifier, password
})
.then(response => {
// Get user data from Strapi
const jwt = response.data.jwt;
console.log("Got token, trying login. Token: ", jwt)
console.log(response.data.user)
// set httponly cookie
res.setHeader(
"Set-Cookie",
cookie.serialize("jwt", jwt, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
maxAge: 60 * 60,
sameSite: "strict",
path: "/",
})
)
console.log("Login successful")
res.status(200).end()
})
.catch(error => {
console.log("Error logging in", error)
res.status(400).end()
})
}
There is a route in Strapi /api/users/me
that you should pass jwt in headers then it will return user data. Note: Always use this route as authenticate route.
try {
const request = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/api/users/me`,
{
method: "GET",
headers: {
Authorization: `Bearer ${jwt}`,// when user login there will be a jwt in reponse so you can pass user jwt in here
},
}
);
const response = await request.json();
console.log(response);//{id : 1 ,email : 'abc@email.com' , username : "abc"}
res.status(200).json(response);
} catch (err) {
res.status(403).json({ msg: "Your are not loggedin" });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.