skip to Main Content

i have a problem when send access tocken in header axios.It returns the following error:

Access to XMLHttpRequest at ‘http://192.168.0.254:3333/api/DOTMobileApi/test’ 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.

I wrote the following codes in react js:

localStorage.setItem("access_token","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmYW1pbHlfbmFtZSI6Itin2YbYtdin2LHZiiIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiLYp9mG2LXYp9ix2YoiLCJuYmYiOjE2NzY0NTMzNTUsImV4cCI6MTY3NjUzOTc1NSwiaXNzIjoibG9jYWxob3N0OjQ0MzQ2IiwiYXVkIjoibG9jYWxob3N0OjQ0MzQ2In0.4w2THPCrSvADow65fEm02H4NWUhGlFblaC6nB6uTgZ8")

let response=  axios.get('http://192.168.0.254:3333/api/DOTMobileApi/test',{ headers:{ 'Authorization': Bearer ${localStorage.getItem("access_token")} } })

console.log(response)

3

Answers


  1. Chosen as BEST ANSWER

    i found solution . i have problem in backend .In fact,app.UseCors("CorsPolicy") should be written before app.UseAuthentication(); app.UseAuthorization()

       public void ConfigureServices(IServiceCollection services)
                {
                    services.AddControllers();
                    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                       .AddJwtBearer(options =>
                       {
                           options.TokenValidationParameters = new TokenValidationParameters
                           {
                               ValidateIssuer = true,
                               ValidateAudience = true,
                               ValidateLifetime = true,
                               ValidateIssuerSigningKey = true,
                               ValidIssuer = Configuration["Tokens:Issuer"],
                               ValidAudience = Configuration["Tokens:Issuer"],
                               IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                               ClockSkew = TimeSpan.Zero,
                           };
                       });
    
    
                    services.AddHttpClient();
                    services.AddMemoryCache();
                    services.AddSession();
                    services.AddResponseCaching();
                    services.AddRazorPages();   
                        
                    services.AddCors(options =>
                    {
                        options.AddPolicy("CorsPolicy",
                            builder => builder.WithOrigins("http://localhost:3000", "http://apirequest.io" )
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials());
                    });
    
    
                    services.AddMvc();
                    services.AddDirectoryBrowser();
                    services.AddAuthorization(options =>
                    {
                        options.FallbackPolicy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
                    });
      
    
                }
    
                public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                {
                    app.UseDeveloperExceptionPage();
                    if (env.IsDevelopment())
                    {
                        app.UseDeveloperExceptionPage();
                    }
                    else
                    {
                        app.UseHsts();
                    }
    
                    app.UseHttpsRedirection();
                    app.UseStaticFiles();
                    app.UseCookiePolicy();
                    app.UseResponseCaching();
    
                    app.Use(async (context, next) =>
                    {
                        context.Response.GetTypedHeaders().CacheControl =
                            new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                            {
                                Public = true,
                                MaxAge = TimeSpan.FromSeconds(100)
                            };
                        context.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.Vary]
    =
                            new string[] { "Accept-Encoding" };
    
                        await next();
                    });
    
    
                    app.UseRouting();   
                    
                    app.UseCors("CorsPolicy");
                    
                    app.UseAuthentication();
                    app.UseAuthorization();
                    app.UseSession();  
                                    
    
                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapControllerRoute("default", "{controller=DOTMobileApi}/{action=Login}/{id?}");
                    });   
    
                   
                }
    

  2. You’ll have to enable CORS in your backend and add localhost:3000 as a trusted domain for this to work

    Login or Signup to reply.
  3. Read about CORS.
    You need to add your host to allowed origins.

    In express without libs your have to do:

    // CORS Middleware
    // ./middlewares/cors.js 
    
    const allowedCors = [
      'http://localhost:3000',
    ];
    
    module.exports = (req, res, next) => {
      const { origin } = req.headers;
    
      if (allowedCors.includes(origin)) {
        res.header('Access-Control-Allow-Origin', origin);
        res.header('Access-Control-Allow-Credentials', 'true');
        const { method } = req;
    
        const DEFAULT_ALLOWED_METHODS = 'GET,HEAD,PUT,PATCH,POST,DELETE';
    
        const requestHeaders = req.headers['access-control-request-headers'];
    
        if (method === 'OPTIONS') {
          res.header('Access-Control-Allow-Methods', DEFAULT_ALLOWED_METHODS);
          res.header('Access-Control-Allow-Headers', requestHeaders);
          return res.end();
        }
      }
      return next();
    };
    

    in app.js:

    const cors = require('./middlewares/cors');
    
    //...
    
    app.use(cors);
    

    Question with you problem:

    No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

    But if its not your API, you need to proxy your requests. Get data on your server and send it to your frontend

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search