Access to XMLHttpRequest at 'API_URL' from origin 'http://localhost:8080' has been blocked by CORS policy:

后端 未结 3 2609
鱼传尺愫
鱼传尺愫 2021-02-20 08:33

Access to XMLHttpRequest at \'API_URL\' from origin \'http://localhost:8080\' has been blocked by CORS policy: Response to preflight request doesn\'t pass a

3条回答
  •  执笔经年
    2021-02-20 09:11

    Best option: CORS header (requires server changes) CORS (Cross-Origin Resource Sharing) is a way for the server to say “I will accept your request, even though you came from a different origin.” This requires cooperation from the server – so if you can’t modify the server (e.g. if you’re using an external API), this approach won’t work.

    Modify the server to add the header Access-Control-Allow-Origin: * to enable cross-origin requests from anywhere (or specify a domain instead of *). This should solve your problem.

    2nd choice: Proxy Server If you can’t modify the server, you can run your own proxy. And this proxy can return the Access-Control-Allow-Origin header if it’s not at the Same Origin as your page.

    Instead of sending API requests to some remote server, you’ll make requests to your proxy, which will forward them to the remote server.

    For first option, If using .Net Core:

           services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
    

    and

    app.UseCors("CorsPolicy");

提交回复
热议问题