当开发中没有问题时,React构建会导致CORS错误

问题描述

我已经构建了一个React应用程序(我的第一个React应用程序),以及一个将数据提供给UI的C#.NET Core 3.1 Web API。我将API和React应用程序部署在同一服务器(Windows 10)上,其中API的端口为3030,React构建的端口为3029,运行命令“ npm run build”生成。 UI的IIS站点指向构建目录。

在我的开发环境中,使用已部署的API运行应用程序是可行的,不需要代理。部署后,我的屏幕加载了,但没有通过FETCH检索到任何记录,而是出现了CORS错误

Access to fetch at 'http://localhost:3030/api/checking' from origin 'http://localhost:3029' has been blocked by CORS policy: 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.

为什么在热加载下用Visual Studio Code在开发中用完React时,此方法为什么起作用?为什么在部署后却不起作用?更重要的是,我该如何工作?

Startup.cs中的API代码

ConfigureServices方法

services.AddCors(options => {
    options.AddDefaultPolicy(builder => {
        builder.WithOrigins(Configuration["AppSettings:CorsUrl"])
        .AllowAnyHeader()
        .AllowAnyMethod();
    });
});

配置方法

app.UseCors();

AppSettings.js代码

  "AppSettings": {
    "CorsUrl": "http://localhost:3029"
  }

反应

我将自己的网址存储在根目录下的.env文件中,如下所示。

REACT_APP_API_URL=http://localhost:3030/api/checking

反应提取命令

在我的checking.js组件中,数据已加载并执行了FETCH。

const SERVER_URL=`${process.env.REACT_APP_API_URL}`

function Checking() {
  const [rowData,setRowData] = useState([]);
  const [newData,setNewData] = useState(initialState);
  const [displayModal,setModaldisplay] = useState(false);
  const columnDeFinitions = Columns();
  const rowDataRef = useRef(rowData);

  useEffect(() => {
    fetch(SERVER_URL)
      .then((response) => response.json())
      .then((rowData) => {
        setRowData(rowData)
        rowDataRef.current = rowData;
      });
  },[]);
.
.
.

解决方法

您需要设置Access-Control-Allow-Origin标头。请尝试以下方法来解决此错误。

1。清除cookie并通过Mod Header扩展名添加Access-Control-Allow-Origin':'*' 再试一次以检查修复程序。

2。尝试使用中间界面控制您的请求并指导他们 进入特殊规则。

 app.use((req,res,next) => {
          res.header('Access-Control-Allow-Origin','*');
          next();
        });
,

事实证明,我注意到某个组件出现异常(ag-grid),并导致我运行npm update。完成后,我重新部署了构建,一切都可以正常工作了。我相信此更新“解决了”问题。