CORS 头部 ‘Access-Control-Allow-Origin’ 丢失。状态码:401 在 React JS 中。

huangapple go评论52阅读模式
英文:

CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401 in react js

问题

当我在axios请求头中发送访问令牌时出现了问题。它返回以下错误:

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.

我在React中编写了以下代码:

localStorage.setItem("access_token", "你的访问令牌")

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

console.log(response)

请注意,你需要将你的访问令牌替换为实际的访问令牌。

英文:

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

得分: 0

你需要在后端启用CORS,并将localhost:3000添加为受信任的域以使其工作。

英文:

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

答案2

得分: 0

阅读关于 CORS 的相关信息。
您需要将您的主机添加到允许的来源列表中。

在 Express 中,如果没有使用第三方库,您需要执行以下操作:

// CORS 中间件
// ./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();
};

在 app.js 中:

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

//...

app.use(cors);

针对您的问题,可以参考以下链接:

https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe

但如果这不是您自己的 API,您需要代理您的请求。在您的服务器上获取数据,然后将其发送到您的前端页面。

英文:

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:

https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe

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

答案3

得分: 0

我找到了解决方法。我的问题在于后端部分。事实上,应该在app.UseAuthentication()之前写上app.UseCors("CorsPolicy")

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

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

               
            }

huangapple
  • 本文由 发表于 2023年2月16日 13:58:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468373.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定