0

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)
  • 1
    If you are running your own backend server, you should enable CORS mechanism in the backend to allow requests from other origin IP adresses – Madhan S Feb 16 '23 at 06:01
  • 2
    Does this answer your question? [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – khangnd Feb 16 '23 at 06:31

3 Answers3

0

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

0

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

rycha
  • 679
  • 2
  • 9
0

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?}");
                });   

               
            }