CORS标题“访问控制-允许-来源”缺失),状态代码:Reactjs中的401

7rfyedvj  于 2023-02-18  发布在  React
关注(0)|答案(4)|浏览(125)

在头axios中发送访问令牌时出现问题。返回以下错误:
CORS策略已阻止从源"http://localhost:3000"访问位于"http://192.168.0.254:3333/api/DOTMobileApi/test"的XMLHttpRequest:对印前检查请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头。
我在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)
nhhxz33t

nhhxz33t1#

您必须在后端启用CORS,并将localhost:3000添加为受信任域,才能使其正常工作

pcww981p

pcww981p2#

了解CORS。您需要将主机添加到允许的起始点。
在没有库的express中,您必须执行以下操作:

// 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();
};

在app.js中:

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

//...

app.use(cors);

您的问题:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
但是如果它不是你的API,你需要代理你的请求,在你的服务器上获取数据并发送到你的前端

wlwcrazw

wlwcrazw3#

我在www.example.com中编写了以下代码startup.ca中asp.net核心API方法与[AllowAnonymous]一起工作,例如登录方法工作。但其他没有[AllowAnonymous]的方法不工作,公共void ConfigureServices(IServiceCollection服务){

//for enable cores 
        // because of api work in react

        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                    builder.WithOrigins("http://localhost:3000", "http://apirequest.io")
                     .AllowAnyOrigin()
                     .AllowAnyHeader()
                     .AllowAnyMethod();
                });
        });

        // Named Policy
        services.AddCors(options =>
        {
            options.AddPolicy(name: "AllowOrigin",
                builder =>
                {
                    builder.WithOrigins("http://localhost:3000", "http://apirequest.io")
                    .AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    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.UseAuthentication();
        app.UseAuthorization();
        app.UseSession();

        // for enable core because of api work in react

        app.UseCors();
        // with a named pocili
        app.UseCors("AllowOrigin");
        // Shows UseCors with CorsPolicyBuilder.
        app.UseCors(builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
        });

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute("default", "{controller=DOTMobileApi}/{action=Login}/{id?}");
        });

       
    }
rkkpypqq

rkkpypqq4#

我找到了解决方案。我在后端有问题。事实上,app.UseCors(“CorsPolicy”)应该在app.UseAuthentication()之前编写;应用程序使用授权()

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

               
            }

相关问题