nextjs:可以在不刷新的情况下获取客户侧cookie
用户登录时,我将cookie设置为js-cookie
用于客户端访问。
cookie必须是-i思考 - 客户可以访问,因为我使用 redux thunk请求 s。
export async function apiLogin({ email, password }) {
const data = JSON.stringify({
email,
password,
});
const config = {
method: 'post',
url: `${process.env.API_URL}/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data,
};
const response = await axios(config);
if (response.status === 200 && response.data) {
const encodedUser = Buffer.from(JSON.stringify(response.data.user)).toString('base64');
Cookies.set('token', response.data.token, { expires: 1 });
Cookies.set('user', encodedUser, { expires: 1 });
return { user: response.data.user, token: response.data.token };
}
if (response.status === 401) {
return { error: 'User/pw incorrect' };
}
return { error: 'Error' };
}
登录时正确设置了这些cookie-我可以在开发工具中的“应用程序”选项卡中看到它们。
但是,这些cookie无法访问我的未来请求:
import Cookies from 'js-cookie';
const cookieToken = Cookies.get('token') // this is throws null unless I refresh
export const axiosInstance = (token = cookieToken) => axios.create({
baseURL: process.env.API_URL,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
});
示例请求:
browse(params = {}, hook = null) {
return axiosInstance()
.get(endpoint, { params })
.then((response) => {
const { data } = response;
if (hook) {
data.items = data.items.map((item) => hook(item));
}
return data;
})
.catch((error) => console.error('error', error));
},
cookie getter方法正常工作,但前提是我刷新页面。所以我认为这不是问题。
编辑:不是axios
问题,我对本机fetch
api做了相同的操作,但仍然无法获得cookie。我还尝试在localstorage
中保存令牌
,结果相同。
EDIT2:
我忘了提到我有一个_MiddleWare.js
文件,仅在存在令牌时才为路由添加保护,这可以正常工作,因此我猜该服务器端可访问该令牌:
export function middleware(req) {
const userSession = req.headers.get('cookie');
const url = req.nextUrl.clone();
if (userSession?.includes('token')) {
console.log(userSession); // token is there!
if (req.nextUrl.pathname === '/login') {
url.pathname = '/';
return NextResponse.redirect(url);
}
return NextResponse.next();
}
url.pathname = '/login';
return NextResponse.rewrite(url);
}
When user logs in, I set the cookies with js-cookie
for client side access.
The cookie must be -I think- client accessible since I use Redux Toolkit for async thunk requests.
export async function apiLogin({ email, password }) {
const data = JSON.stringify({
email,
password,
});
const config = {
method: 'post',
url: `${process.env.API_URL}/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data,
};
const response = await axios(config);
if (response.status === 200 && response.data) {
const encodedUser = Buffer.from(JSON.stringify(response.data.user)).toString('base64');
Cookies.set('token', response.data.token, { expires: 1 });
Cookies.set('user', encodedUser, { expires: 1 });
return { user: response.data.user, token: response.data.token };
}
if (response.status === 401) {
return { error: 'User/pw incorrect' };
}
return { error: 'Error' };
}
Those cookies are correctly set upon login - I can see them in the application tab in Dev Tools.
However, those cookies are not accessible to my future requests:
import Cookies from 'js-cookie';
const cookieToken = Cookies.get('token') // this is throws null unless I refresh
export const axiosInstance = (token = cookieToken) => axios.create({
baseURL: process.env.API_URL,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`,
},
});
Example request:
browse(params = {}, hook = null) {
return axiosInstance()
.get(endpoint, { params })
.then((response) => {
const { data } = response;
if (hook) {
data.items = data.items.map((item) => hook(item));
}
return data;
})
.catch((error) => console.error('error', error));
},
The cookie getter methods work fine, but only If I refresh the page. So I don't think that's the issue.
EDIT: Is not an axios
issue, I did the same with the native fetch
API and still couldn't get the cookies. I also tried saving the token
in localStorage
with the same result.
EDIT2:
I forgot to mention that I have a _middleware.js
file that adds protection to routes only if the token is present, and this works fine, so I guess that server side the token is accessible:
export function middleware(req) {
const userSession = req.headers.get('cookie');
const url = req.nextUrl.clone();
if (userSession?.includes('token')) {
console.log(userSession); // token is there!
if (req.nextUrl.pathname === '/login') {
url.pathname = '/';
return NextResponse.redirect(url);
}
return NextResponse.next();
}
url.pathname = '/login';
return NextResponse.rewrite(url);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的,损失了很多时间修复此操作,这让您感到有些尴尬,但是显然,设置了一个cookie令牌,
> soken
不起作用,在尝试了其他几种方法之后,它看起来就是简单地命名它cookietoken
做了这项工作。 lmao。Ok it feel kind of embarassed to have lost so much time fixing this, but apparently setting a cookie token with a name of
token
was not working, after trying several other methods, it looks like that simply naming itcookieToken
did the work. Lmao.