简体   繁体   English

如何启用 CORS 并使其在 Asp.net 核心 Web ZDB97423871438ACF19393F20C1EC91B750799EC5EEBZ 中正常工作

[英]How to enable CORS and make it work properly with POST in Asp.net Core Web API?

I am trying to create web api using Asp.net Core Web Api and as a front-end i am using React.js. I am trying to create web api using Asp.net Core Web Api and as a front-end i am using React.js. I have done everything what the official Microsoft Doc says to enable CORS and tried every solution on here but it is not working to POST request.我已经完成了官方 Microsoft Doc 所说的一切以启用 CORS 并在此处尝试了所有解决方案,但无法发布请求。 What am i doing wrong here?我在这里做错了什么?

I am adding on ConfigureService in Startup.cs :我在Startup.cs中添加ConfigureService

services.AddCors();

and on Configure并在Configure

 app.UseCors(builder => builder.WithOrigins("https://localhost:PORT_NUMBER")
 .AllowAnyHeader()
 .AllowAnyMethod()
 .SetIsOriginAllowed((host) => true)
 .AllowCredentials()
);

What is wrong with this code?这段代码有什么问题? and on frond-end part I am using fetch() to POST items to the backend, it is working fine to fetch items from backend using GET but not with POST:在前端部分,我使用 fetch() 将项目发布到后端,使用 GET 从后端获取项目但不使用 POST 可以正常工作:

fetch(url, {
        method: 'POST',
        body: JSON.stringify({
            Ins_Emp: "Ins_Emp",
            Up_Emp: "Up_Emp",
            Item_Code: "Item_Code",
            Item_Name: "Item_Name",
            Item_Spec: "Item_Spec",
            Remark: "Remark",
            Unit_Code: "Unit_Code",
            Up_DateTime: null,
            Ins_DateTime: null,
            Use_YN: null
        }),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=utf-16',
        },

I am getting this error from developer tool panel: console我从开发人员工具面板收到此错误:控制台

在此处输入图像描述

Both backend and frontend is being developed on the same laptop on localhost with different port number.后端和前端都是在 localhost 上的同一台笔记本电脑上开发的,具有不同的端口号。

Personally, I will not enable CORS, because you eventually have to disable it in production and that may have unexpected side effects.就个人而言,我不会启用 CORS,因为您最终必须在生产中禁用它,这可能会产生意想不到的副作用。

Instead, use a proxy during development so that certain URLs (eg /api/* ) are proxied to the server side.相反,在开发过程中使用代理,以便将某些 URL(例如/api/* )代理到服务器端。

I assume you are using Create React App, please update me if this is not the case.我假设你正在使用 Create React App,如果不是这样,请更新我。

Solution for CRA: https://create-react-app.dev/docs/proxying-api-requests-in-development CRA 解决方案: https://create-react-app.dev/docs/proxying-api-requests-in-development

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM