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

React(Vite)配置代理解决CORS错误却遇404问题求助

解决Azure AD Token获取的Vite代理404问题

问题描述

在React(Vite)项目中通过axios请求Azure AD获取Token,配置Vite代理后出现POST http://localhost:portNumber/api/Token 404 (Not Found)错误,但Postman可正常获取Token,Azure SPA应用配置无误。

解决方案

1. 修正Vite代理的路径重写规则

原代理配置会将/api/token转发到https://login.microsoftonline.com/tenantId/oauth2/v2.0/api/token,但Azure AD的Token端点是https://login.microsoftonline.com/tenantId/oauth2/v2.0/token,需要添加路径重写去掉/api前缀:

// vite.config.ts
export default defineConfig({
  // ...其他配置
  server: {
    proxy: {
      '/api': {
        target: 'https://login.microsoftonline.com/tenantId/oauth2/v2.0',
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path.replace(/^\/api/, '') // 移除/api前缀
      }
    }
  }
})

2. 修正请求参数的编码格式

因为设置了Content-Type: application/x-www-form-urlencoded,直接传JSON对象会导致参数解析失败,需用URLSearchParams格式化参数:

import axios from "axios";
const index = () => {
  console.log("Fetching the API Token");
  // 用URLSearchParams处理参数
  const bodyParameters = new URLSearchParams({
    client_id: "--------------",
    client_secret: "------------------",
    grant_type: "client_credentials",
    scope: "--------------",
  });
  const instance = axios.create({
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
  return instance
    .post("/api/token", bodyParameters) // 确保路径是小写的/token
    .then((response) => {
      console.log(response.data);
      console.log("API Token fetched successfully");
    })
    .catch((err) => {
      console.log(err);
      console.log("Error happened for fetching API Token");
    });
};

export default index;

3. 统一请求端点的大小写

错误中请求的是/api/Token(首字母大写),而Azure AD的端点是全小写的/token,需确保axios请求的路径为/api/token,避免大小写不匹配导致404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:31:03