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

本文标签: