跨源请求被阻止,即使它以 200 ok 状态代码响应
Cross-Origin Request Blocked even though it responds with 200 ok status code
伙计们,我正在开发全栈 React.js - ASP.NET Core 5 应用程序。后端已完成(经过全面测试)。当然,它包含一个 CORS 策略以允许来自客户端的请求,但是当我尝试使用 axios 从 react 发送请求时,axios 抛出网络错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/customers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
我看到服务器发送了正确的响应(我什至可以调试服务器)但 axios 仍然失败。我只是试图通过在 package.json
:
中包含一个代理来解决它
"proxy": "https://localhost:5001"
我将包含我的 app.js
请求代码和 startup.cs
代码,因为它包含 CORS 策略:
客户端
const fetchCustomers = async () => {
const customers = await axios.get(customersApiUrl);
console.log(customers);
setCustomers(customers);
setIsLoading(false);
};
服务器
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000/");
builder.AllowAnyHeader();
builder.AllowAnyMethod();
});
});
services.AddControllers();
services.AddDbContextPool<TwinEnginesDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Standard")));
services.AddScoped<ICustomerTypeRepository, CustomerTypeRepository>();
services.AddScoped<ICustomerTypeService, CustomerTypeService>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<ICustomerService, CustomerService>();
services.AddAutoMapper(Assembly.GetExecutingAssembly());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
已编辑: 我包括 CustomersController.cs
代码以及来自 HTTP 请求的详细信息。
CustomersController.cs
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
private readonly ICustomerService _customerService;
private readonly ICustomerTypeService _typeService;
private readonly IMapper _mapper;
public CustomersController(ICustomerService customerService, ICustomerTypeService typeService, IMapper mapper)
{
this._customerService = customerService ?? throw new ArgumentNullException(nameof(customerService));
this._typeService = typeService ?? throw new ArgumentNullException(nameof(typeService));
this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
// [EnableCors("MyAllowSpecificOrigins")]
[HttpGet("")]
public async Task<ActionResult<IEnumerable<CustomerDTO>>> GetCustomers()
{
var customers = await _customerService.GetAllAsync();
var response = _mapper.Map<IEnumerable<CustomerDTO>>(customers);
return Ok(response);
}
}
请求图片:
任何想法,想法?我真的需要你们的帮助,这是开发工作的技术任务。
尝试将此属性添加到您的控制器
[EnableCors(MyAllowSpecificOrigins)]
尝试使用没有
末尾的斜线:builder.WithOrigins("http://localhost:3000");
更改后请清理并重建项目,因为这可能是个问题。
此外,您不需要在 JS 端设置代理。
P.S。请求的 mode
可能未在 Axios 端正确设置。如果上述解决方案不起作用,请尝试使用:
axios(requestURL, { mode: 'cors' })
伙计们,我正在开发全栈 React.js - ASP.NET Core 5 应用程序。后端已完成(经过全面测试)。当然,它包含一个 CORS 策略以允许来自客户端的请求,但是当我尝试使用 axios 从 react 发送请求时,axios 抛出网络错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5001/api/customers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
我看到服务器发送了正确的响应(我什至可以调试服务器)但 axios 仍然失败。我只是试图通过在 package.json
:
"proxy": "https://localhost:5001"
我将包含我的 app.js
请求代码和 startup.cs
代码,因为它包含 CORS 策略:
客户端
const fetchCustomers = async () => {
const customers = await axios.get(customersApiUrl);
console.log(customers);
setCustomers(customers);
setIsLoading(false);
};
服务器
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000/");
builder.AllowAnyHeader();
builder.AllowAnyMethod();
});
});
services.AddControllers();
services.AddDbContextPool<TwinEnginesDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Standard")));
services.AddScoped<ICustomerTypeRepository, CustomerTypeRepository>();
services.AddScoped<ICustomerTypeService, CustomerTypeService>();
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<ICustomerService, CustomerService>();
services.AddAutoMapper(Assembly.GetExecutingAssembly());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
已编辑: 我包括 CustomersController.cs
代码以及来自 HTTP 请求的详细信息。
CustomersController.cs
[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
private readonly ICustomerService _customerService;
private readonly ICustomerTypeService _typeService;
private readonly IMapper _mapper;
public CustomersController(ICustomerService customerService, ICustomerTypeService typeService, IMapper mapper)
{
this._customerService = customerService ?? throw new ArgumentNullException(nameof(customerService));
this._typeService = typeService ?? throw new ArgumentNullException(nameof(typeService));
this._mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
// [EnableCors("MyAllowSpecificOrigins")]
[HttpGet("")]
public async Task<ActionResult<IEnumerable<CustomerDTO>>> GetCustomers()
{
var customers = await _customerService.GetAllAsync();
var response = _mapper.Map<IEnumerable<CustomerDTO>>(customers);
return Ok(response);
}
}
请求图片:
尝试将此属性添加到您的控制器
[EnableCors(MyAllowSpecificOrigins)]
尝试使用没有
末尾的斜线:builder.WithOrigins("http://localhost:3000");
更改后请清理并重建项目,因为这可能是个问题。
此外,您不需要在 JS 端设置代理。
P.S。请求的 mode
可能未在 Axios 端正确设置。如果上述解决方案不起作用,请尝试使用:
axios(requestURL, { mode: 'cors' })