英文:
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);
针对您的问题,可以参考以下链接:
但如果这不是您自己的 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:
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?}");
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论