Esm*_*ari 5 session laravel axios laravel-sanctum
我的网站有 laravel 作为后端,next.js 作为前端。我使用 laravel sainttum 进行身份验证。
我的 laravel 应用程序和 next.js 应用程序位于同一主机中,然后我可以使用基于会话的密室进行身份验证,而无需使用令牌。
登录后,当我想访问 next.js 客户端中受中间件 aute:sanctum 保护的路由时,没有问题,但在服务器端总是出现未经验证的错误。
这是我的 axios 配置和在 next.js 中获取数据的函数:
// axios instance
const axiosInstance = axios.create({
baseURL: 'localhost:8000',
withCredentials: true,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
});
const onRequest = (config) => {
if ((
config.method == 'post' ||
config.method == 'put' ||
config.method == 'delete'
/* other methods you want to add here */
) &&
!Cookies.get('XSRF-TOKEN')) {
return setCSRFToken()
.then(response => config);
}
return config;
}
const setCSRFToken = () => {
return axiosInstance.get('api/v1/csrf-cookie');
}
// attach your interceptor
axiosInstance.interceptors.request.use(onRequest, null);
// fetch data:
export async function getServerSideProps(context) {
const { query, req } = context;
const {
page,
search_term,
nip,
tableName
} = query;
try {
const response = await ax.post(`api/v1/admin/${tableName}`, { page: page, search_term: search_term, nip: nip || 10 }, {
withCredentials: true,
headers: {
Cookie: req.headers.cookie,
}
});
return {
props: {
initItems: response.data.data,
initMeta: response.data.meta,
initSearchTerm: search_term || '',
iniNip: nip || 10
}
}
} catch (err) {
console.log(err);
return {
notFound: true,
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1092 次 |
最近记录: |