![](/img/trans.png)
[英]AWS - has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
[英]react Access to XMLHttpRequest has been blocked by CORS policy No 'Access-Control-Allow-Origin' header is present on the requested resource
我正在尝试从 api 访问数据,但出现此错误
从源“ http://localhost:3000 ”访问“ http://example.com/api/login ”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否“访问” -Control-Allow-Origin' 标头存在于请求的资源上。
这是我的代码
return axios.post('http://example.com/api/login', { username: username, password: password }).then(response => {
console.log('response', response);
if (response.status === 400 || response.status === 500)
throw response.data;
return response.data;
}).catch(err => {
console.log('err', err);
throw err[1];
});
使用 asp.net 构建的后端
谢谢
此问题与您的服务器有关。 您的服务器不允许来自不同域的请求。 在您的情况下, http://example.com/api/login
和http://localhost:3000
在不同的域中。 你可以在你的 asp.net 代码中允许任何你想要的域。 以下代码可能对您有用:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseMvc();
}
}
有关更多信息,您可以在此处导航
经过数小时的搜索,我发现这个 chrome 扩展可以解决这个问题https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.