简体   繁体   中英

CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource

I would like to POST data from a Font-end form (coded in REACT) to an API Server (coded in C#).

To do so, I coded the following:

For the Front-end:

const [analysis, setAnalysis] = useState(null);

const headers = {
    'Content-Type': 'application/json;charset=UTF-8',
    "Access-Control-Allow-Origin": "*",
    'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
    'Access-Control-Allow-Headers': '*'
};


useEffect(() => {
    axios.get(baseURL, {
        mode: 'cors',
        headers: headers,
    }).then((response) => {
        setAnalysis(response.analysis);
    });
}, []);

For the Back-end:

builder.Services.AddCors(options =>
{
    options.AddPolicy("MyMyAllowCredentialsPolicy",
        builder =>
        {
            builder.AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true) // allow any origin
                .AllowCredentials(); // allow credentials
        }
    );
}); 

Nevertheless, I have the following issue: 在此处输入图像描述

I tried so many different configurations, but nothing worked. Does someone have any idea what is the problem and how to solve it?

Thank you in advance, Alexia


[Edition]

Following all the advises, I changed my code.

The Front-end part:

const headers = {
        'Content-Type': 'application/json;charset=UTF-8',
    };


    useEffect(() => {
        axios.get(baseURL, {
            mode: 'cors',
            headers: headers,
        }).then((response) => {
            setAnalysis(response.analysis);
        });
    }, []);

The back-end:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
{
    options.AddPolicy(MyAllowSpecificOrigins,
                          builder =>
                          {
                              builder.WithOrigins("http://localhost:3000/")
                                                  .AllowAnyHeader()
                                                  .AllowAnyMethod();
                          });
});

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


var app = builder.Build();

app.UseCors(MyAllowSpecificOrigins);

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

With this configuration I still have:

Access to XMLHttpRequest at 'https://localhost:7067/...?id=1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I had a similar issue and had to do changes to the actual API code, so on your Start.cs add the following. I recommend trying it first in localhost and then deploying the changes where you actually have the API.

public class Startup
{
    private readonly string _MyCors = "MyCors";
    .
    .
    .
    public void ConfigureServices(...)
    {
        .
        .
        .
        //Under your services.AddControllers();
        services.AddCors(options =>
        {
            options.AddPolicy(name: _MyCors, builder =>
            {
                //for when you're running on localhost
                builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") 
                .AllowAnyHeader().AllowAnyMethod();


                //builder.WithOrigins("url from where you're trying to do the requests")
            });
        });
    }
    public void Configure(.....)
    {
        //before the app.UseAuthorization & app.UseEndpoints
        app.UseCors(_MyCors);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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