繁体   English   中英

如何让我的 C# API 响应来自我的 React 应用程序的 POST 请求? (CORS问题)

[英]How can I get my C# API to respond to a POST request from my React app? (CORS issue)

我有一个 React 应用程序,它通过 POST 方法将 JSON object 发送到我的 API。 我可以使用 Post-man 得到适当的响应,但在我的应用程序中,存在 CORS 问题。 我希望能够将 object 发送到我的 API,并让 API 发回书面文件。 我的 GET 方法可以正常工作。

以下是我得到的错误:

    xhr.js:166 OPTIONS http://localhost:57429/api/MiniEntity 404 (Not Found)

    Access to XMLHttpRequest at 'http://localhost:57429/api/MiniEntity' from origin 
    'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't 
    pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested 
    resource.

这是我的反应代码:

    var apiUrl = "http://localhost:57429/api/MiniEntity";
    axios.post(apiUrl, this.state.entitiesToExport).then(response => {
        console.log(response.data);
    });

这是我的 C# API 代码:

    // Post: api/MiniEntity
    [HttpPost]
    public HttpResponseMessage PostMiniEntities([FromBody] object value)
    {
        HttpContext.Response.Headers.Add("access-control-allow-origin", "*");
        var json = JsonConvert.SerializeObject(value);
        System.IO.File.WriteAllText("output.txt", json);
        var dataBytes = System.IO.File.ReadAllBytes("output.txt");
        var dataStream = new MemoryStream(dataBytes);

        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        httpResponseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
        httpResponseMessage.Content = new StreamContent(dataStream);
        httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = "output.txt";
        httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
        httpResponseMessage.Content.Headers.Add("Access-Control-Allow-Origin", "*");
        httpResponseMessage.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
        httpResponseMessage.Headers.Add("Access-Control-Allow-Methods", "POST, OPTIONS");

        return httpResponseMessage;
    }

所有 header 的东西都是我试图允许访问,但它不起作用。

Postman 不属于任何来源,这就是请求通过的原因。

  1. Startup.cs > ConfigureServices 方法 > 添加这一行 services.AddCors();
  2. Startup.cs > Configure 方法添加这个: app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

这将通过所有应用程序启用 CORS。

暂无
暂无

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

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