admin管理员组文章数量:1123712
I tried using the server/api/[...].ts in my project with the following code:
import { joinURL } from 'ufo';
export default defineEventHandler(async (event) => {
const proxyUrl = useRuntimeConfig().myProxyUrl;
const path = event.path.replace(/^\/api\//, '');
const target = joinURL(proxyUrl, path);
return proxyRequest(event, target);
});
Then, I created a store using Pinia with the following code:
import { defineStore } from 'pinia';
interface UserPayloadInterface {
email: string;
password: string;
}
export const useAuthStore = defineStore('auth', {
state: () => ({
authenticated: useCookie('authenticated') || null,
token: useCookie('token') || null,
loading: false,
error: null,
message: null,
}),
actions: {
async authenticateUser(index: UserPayloadInterface) {
const axios = useNuxtApp().$axios;
this.loading = true;
try {
const response = await axios.post('/auth/login', index);
if (response.data.data) {
const tokenRefresh = useCookie('tokenRefresh');
tokenRefresh.value = response.data?.data?.refreshToken;
const token = useCookie('token');
token.value = response.data?.data?.token;
const authentication = useCookie('isAuth');
authentication.value = 'true';
this.loading = false;
this.token = token.value;
this.authenticated = authentication.value;
navigateTo('/dashboard');
}
} catch (err: any) {
this.error = err.response.data.errors || 'Unknown error';
this.loading = false;
this.authenticated = null;
}
},
async logUserOut() {
const { $axios } = useNuxtApp();
try {
const response = await $axios.post('/auth/logout', {
headers: {
authorization: this.token,
},
});
if (response.data) {
const token = useCookie('token');
const tokenRefresh = useCookie('tokenRefresh');
const authenticated = useCookie('isAuth');
authenticated.value = null;
tokenRefresh.value = null;
token.value = null;
this.authenticated = null;
navigateTo('/login');
}
} catch (err: any) {
this.error = err.data.errors;
console.log(this.error, 'This is the error');
}
},
},
});
then , i created a axios interceptor :
export default defineNuxtPlugin((nuxtApp) => {
const axiosInstance = axios.create({
baseURL: '/api',
withCredentials: true,
})
axiosInstance.interceptors.request.use(
(config) => {
const store = useAuthStore()
if (store.token) {
config.headers.Authorization = store.token
}
if (!config.responseType) {
config.responseType = "json";
}
return config
},
(error) => {
// Handle request error
return Promise.reject(error)
},
)
axiosInstance.interceptors.response.use(
(response) => {
return response
},
async (error) => {
const originalRequest = error.config
if (error.response && error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true
try {
const refreshToken = useCookie('tokenRefresh')
if (refreshToken.value) {
const form = {
refreshToken: refreshToken.value,
}
const refreshResponse = await axiosInstance.post(
'/auth/refresh-token',
form,
)
const newToken = refreshResponse.data?.accessToken
if (newToken) {
const store = useAuthStore()
store.token = newToken
const token = useCookie('token')
token.value = newToken
originalRequest.headers['Authorization'] = `${newToken}`
return axiosInstance(originalRequest)
} else {
const token = useCookie('token')
token.value = null
const tokenRefresh = useCookie('tokenRefresh')
tokenRefresh.value = null
const isAuth = useCookie('isAuth')
isAuth.value = null
navigateTo('/login')
return Promise.reject(error)
}
} else {
const token = useCookie('token')
token.value = null
const tokenRefresh = useCookie('tokenRefresh')
tokenRefresh.value = null
const isAuth = useCookie('isAuth')
isAuth.value = null
navigateTo('/login')
return Promise.reject(error)
}
} catch (refreshError) {
const store = useAuthStore()
store.logUserOut()
const token = useCookie('token')
token.value = null
const tokenRefresh = useCookie('tokenRefresh')
tokenRefresh.value = null
const isAuth = useCookie('isAuth')
isAuth.value = null
navigateTo('/login')
return Promise.reject(error)
}
}
return Promise.reject(error)
},
)
return {
provide: { axios: axiosInstance },
}
})
The issue occurs at production after npm run build , when I receive a successful response I get response.data as a Blob, but when there's an error, such as incorrect email or password, I get a JSON response. I've already checked the backend, and everything works fine in Postman and cURL where the response is in JSON format.
.png .png
本文标签:
版权声明:本文标题:typescript - Nuxt 3 auth when try login if bad request response is json, but when request ok not json ( on production ) - Stack 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736585376a1945004.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论