Nx React - 代理无法与 Nx 和 React 一起使用

Sab*_*kya 7 proxy cors reactjs nrwl-nx

我有一个使用 Nx 创建的 React 应用程序,我试图对我的开发服务器进行 api 调用,但遇到了 CORS 问题。所以我尝试按照此链接设置代理:https://nx.dev/l/r/tutorial/06-proxy#react-nx-tutorial---step-6-proxy-configuration

在我的项目服务器中,我添加了:

工作空间.json 或项目.json

"serve": {
      "executor": "@nrwl/web:dev-server",
      "options": {
        "buildTarget": "my-app:build",
        "hmr": true,
        "proxyConfig": "apps/my-app/proxy.conf.json"
      },
Run Code Online (Sandbox Code Playgroud)

和 proxy.conf.json:

{
  "/my-context-path/api/v1": {
    "target": "https://my-dev-server.com",
    "secure": true
  }
}
Run Code Online (Sandbox Code Playgroud)

并将 api 调用设置为:

export async function getInfo(planId, nbr) {
   return  await fetch(`/my-context-path/api/v1/getInfo?planId=${planId}&nbr=${nbr}`, {
     method: 'GET',
     headers: {
       'Authorization': 'Basic authHeader',
       'Content-Type': 'text/plain',// adding or removing this header is making no difference
     }
   }).then(async (response) => {
      // success block
   }).catch(async (error) => {
     // failure block
   })
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我设置代理时,出现 404 未找到错误。如果我不使用代理直接访问服务器,就会遇到 CORS 问题。

在此输入图像描述

被调用的网址为: https://localhost:4200/my-context-path/api/v1/getInfo?planId=<...data>&irsNbr=<...data>

注意:后端服务器已经启用了Cors。

有人可以帮助我解决这个问题或指出我遗漏或做错了什么吗?

更新:找到解决方案!我在 proxy.conf.json 中添加了 "changeOrigin": true 并重新启动了我的系统,然后它开始正常工作。但我还是不明白为什么重启系统就可以了。可能是某种缓存问题,我还不清楚。

proxy.conf.json - 更新

{
  "/my-context-path/api/v1": {
    "target": "https://my-dev-server.com",
    "secure": true,
    "changeOrigin": true
  }
}
Run Code Online (Sandbox Code Playgroud)