You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中使用React Query调用接口时出现Axios CORS错误

解决NextJS中React Query useMutation请求的CORS问题

我在NextJS应用里,基于@tanstack/react-query的useMutation封装了useDCMSdata Hook,通过Axios向指定POST接口请求数据,但目前遇到了CORS错误,怀疑是代码语法问题,查阅TanStack文档后仍未定位到问题。

封装的useDCMSdata Hook代码

import { useMutation } from '@tanstack/react-query'
import axios from 'axios'
import { DCMSRequestData, DCMSResponse } from '@/types/DCMSdata'

export default function useDCMSdata() {
  return useMutation<DCMSResponse, Error, DCMSRequestData>({
    mutationFn: async (requestData: DCMSRequestData) => {
      return axios
        .post(
          'https://supply-chain-wms-api-public-develop-internal-eks.eu-west-1.dev.hbi.systems/api/v1/order/query',
          requestData,
          {
            headers: {
              'Content-Type': 'application/json',
              'x-hbi-app-name': 'local-testing',
              Connection: 'keep-alive',
            },
            withCredentials: true,
          },
        )
        .then((response) => response.data)
    },
  })
}

组件中调用mutate的代码

useEffect(() => {
    const requestData: DCMSRequestData = {
      warehouse_ids: ['TestTransfer'],
      // statuses: ['string'],
      // orderTypes: ['string'],
      // transferIds: [0],
      page_size: 100,
      page: 1,
    }

    mutate(requestData, {
      onSuccess: (responseData) => {
        const fetchedOrders = responseData.data.data.map((order) => ({
          id: order.id,
          warehouseId: order.warehouse_id,
          status: order.status,
          transferId: order.transfer_id,
          selected: selectedIds.includes(order.id),
        }))
        setRows(fetchedOrders)
      },
      onError: (error) => {
        console.error('Error fetching data:', error)
      },
    })
  }, [mutate, selectedIds])

CORS错误截图

CORS错误截图

问题分析与解决方向

你的代码语法本身没有明显错误,CORS问题本质是浏览器的跨域安全限制,和React Query、Axios的语法关联不大,以下是具体排查和解决方法:

  • 检查后端接口的CORS配置:目标接口需要配置允许你的前端域名(比如本地开发的http://localhost:3000)发起跨域请求,同时要允许Content-Type、x-hbi-app-name这些自定义请求头,还要开启Access-Control-Allow-Credentials: true(因为你设置了withCredentials: true)。如果是内部接口,联系后端团队确认是否添加了对应的CORS规则。

  • 使用NextJS本地代理绕过CORS:本地开发阶段,可以通过NextJS的代理配置转发请求,避免浏览器的跨域限制。在项目根目录的next.config.js中添加以下配置:

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      async rewrites() {
        return [
          {
            source: '/api/v1/order/query',
            destination: 'https://supply-chain-wms-api-public-develop-internal-eks.eu-west-1.dev.hbi.systems/api/v1/order/query',
          },
        ]
      },
    }
    
    module.exports = nextConfig
    

    之后把Axios的请求地址改成/api/v1/order/query,本地请求会被NextJS代理转发,从而绕过CORS限制。

  • 验证OPTIONS预检请求:浏览器发送POST请求前会先发送OPTIONS预检请求,确认是否允许跨域。如果OPTIONS请求失败,就会触发CORS错误。可以在浏览器开发者工具的Network面板查看OPTIONS请求的响应状态和头信息,确认后端是否正确处理了预检请求。

内容的提问来源于stack exchange,提问作者Mo Miah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 10:44:54