Next.js 14 的 RTK 查询问题:RTK 查询会出现 CORS 策略问题,但 Axios 不会出现问题

问题描述 投票:0回答:1

我正在构建 Next.js 14 应用程序,并且在 RTK 查询中遇到此错误: 我正在使用 Next JS 14 redux 工具包

这是我的 RTK 查询:

import { BaseQueryApi, FetchArgs, RootState, createApi, fetchBaseQuery } from  '@reduxjs/toolkit/query/react'
import { setCredentials, logOut } from '@/store/slices/auth/authSlice'

const baseQuery = fetchBaseQuery({
    baseUrl: 'https://xxxxxxxxxx.amazonaws.com/dev/login/admin',
    method: 'POST',
    body: {
        "emailAddress": "[email protected]",
        "password": "Visio@1234"
    },
    credentials: 'include',
    prepareHeaders: (headers, { getState }) => {
        const token = getState().auth.token
        if (token) {
            //headers.set("authorization", `Bearer ${token}`)
            headers.set("x-api-key", `WhKzV4ZUxaaao8w7ytOcc5kQt169ffpQhDHQlBf4TiDrFIF`)
        }
        return headers
    }
})

const baseQueryWithReauth = async (args, api, extraOptions) => {
    let result = await baseQuery(args, api, extraOptions)

    if (result?.error?.originalStatus === 403) {
        console.log('sending refresh token')

        const refreshResult = await baseQuery('/refresh', api, extraOptions)
        console.log(refreshResult)
        if (refreshResult?.data) {
            const user = api.getState().auth.user
   
            api.dispatch(setCredentials({ ...refreshResult.data, user }))
    
            result = await baseQuery(args, api, extraOptions)
        } else {
            api.dispatch(logOut())
        }
    }

    return result
}

export const apiSlice = createApi({
    baseQuery: baseQueryWithReauth,
    endpoints: builder => ({})
})

这就是我遇到 Cors 问题的方式:

https://xxxxx.amazonaws.com/dev/login/admin/auth' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

但是如果我不使用 RTK 查询,cors 问题就不会出现: 这是我使用axios的代码

const axios = require('axios');

const baseQuery = async (getState) => {
    // Extract the token from the state
    const token = getState().auth.token;
    // Prepare the headers
    const headers = {
        'Content-Type': 'application/json',
    };
    if (token) {
        // headers['Authorization'] = `Bearer ${token}`;
        headers['x-api-key'] = 'WhKzV4ZUxo8wzxc7ytO5kQt169pQhDHQzxclBf4TiDrFIF';
    }
    // Make the POST request using Axios
    try {
        const response = await axios.post(
            'https://xxxxxxx.amazonaws.com/dev/login/admin',
            {
                emailAddress: '[email protected]',
                password: 'Visio@1234',
            },
            {
                headers: headers,
                withCredentials: true,
            }
        );
        return response.data;
    } catch (error) {
        console.error('Error making request:', error);
        throw error;
    }
};
// Example usage:
// Assuming you have a function to get the state
const getState = () => ({
    auth: {
        token: 'your_token_here', // Replace with actual token retrieval logic
    },
});
// Call the baseQuery function with the state
baseQuery(getState).then(data => {
    console.log('Response data:', data);
}).catch(error => {
    console.error('Request failed:', error);
});

如何解决这个问题?

next.js redux cors rtk-query
1个回答
2
投票

此 Web 服务阻止了 Cores

https://xxxxx.amazonaws.com/dev/login/admin/auth
检查是否有办法从此 Web 服务端启用 Cors。

© www.soinside.com 2019 - 2024. All rights reserved.