How to allow CORS in react.js?

后端 未结 8 1597
[愿得一人]
[愿得一人] 2020-12-25 12:11

I\'m using Reactjs and using API through AJAX in javascript. How can we resolve this issue? Previously I used CORS tools, but now I need to enable CORS.

8条回答
  •  失恋的感觉
    2020-12-25 12:34

    I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.

    in the request, you must set in header Content-Type:

    Axios({
                method: 'post',
                headers: { 'Content-Type': 'application/json'},
                url: 'https://localhost:44346/Order/Order/GiveOrder',
                data: order,
              }).then(function (response) {
                console.log(response);
              });
    

    and in backend (Asp .net core API) u must have some setting:

    1. in Startup --> ConfigureServices:

    #region Allow-Orgin
                services.AddCors(c =>
                {
                    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
                });
                #endregion
    

    2. in Startup --> Configure before app.UseMvc() :

    app.UseCors(builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
    

    3. in controller before action:

    [EnableCors("AllowOrigin")]
    

提交回复
热议问题