服务器从API获取JWT,客户端如何从服务器获取JWT ?



我正在使用Next.js和Strapi进行身份验证。客户端向Next.js服务器发送带有凭据的post请求。然后,服务器向Strapi API发送一个post请求,传递凭据,让用户登录。服务器获取JWT令牌并将其设置为HTTPonly cookie。

我的问题是:我如何在客户端接收JWT来做一些抓取?我真不知道该怎么做。

客户端发送post请求和凭据到服务器:

// -- /pages/account/login.js
const handleLogin = (e) => {
e.preventDefault()
axios.post("/api/login", {
identifier: `${credentials.email}`,
password: `${credentials.password}`,
remember: stayLoggedIn,
})
.then(response => {
// I need to access the JWT here
Router.push("/")
response.status(200).end()
}).catch(error => {
console.log("Error reaching /api/login ->", error)
})
}

服务器调用Strapi API并登录用户,接收JWT令牌并将其设置为cookie:

// -- /pages/api/login.js
export default (req, res) => {
const {identifier, password, remember} = req.body;
// Authenticate with Strapi
axios.post(`${API_URL}/api/auth/local`, {
identifier, password
})
.then(response => {
const jwt = response.data.jwt; // I need to pass this back to client
console.log("Got token: ", jwt)
// Set HTTPonly cookie
if (remember === false) {
res.setHeader(
"Set-Cookie",
cookie.serialize("jwt", jwt, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
maxAge: 60 * 60 * 24, // Logged in for 1 day
sameSite: "strict",
path: "/",
})
)
} else {
//...
}
console.log("Login successful")
res.status(200).end()
})
.catch(error => {
console.log("Error logging in", error)
res.status(400).end()
})
}

服务器从请求接收到的JWT必须发送回客户端。我该怎么做呢?我好像迷路了……谢谢!

明白了。我可以用res.status(200).end(dataFromServer)。我知道这很简单。

最新更新