【发布时间】:2020-08-25 21:30:59
【问题描述】:
我在 csharp web api 中创建了一个端点,它返回一些 json 数据,它在邮递员上运行良好。 但是当我在我的反应应用程序上尝试相同的网址时,我收到以下错误
反应代码
fetch('https://localhost:44391/agency')
.then(response => response.json())
.then(json => console.log(json))
错误
Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我点击了这个链接Trying to use fetch and pass in mode: no-cors 并尝试了以下代码
fetchData () {
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'https://localhost:44391/agency'
fetch(proxyUrl + targetUrl)
.then(blob => blob.json())
.then(data => {
console.log(data);
return data;
})
.catch(e => {
console.log(e);
return e;
});
}
我收到此错误
GET https://cors-anywhere.herokuapp.com/https://localhost:44391/agency 404 (Not Found)
SyntaxError: Unexpected token N in JSON at position 0
注意 我无法执行的链接中的步骤是
git clone https://github.com/Rob--W/cors-anywhere.git - 完成
cd cors-anywhere/ - 完成
npm 安装 - 完成
heroku create - 不能这样做。我需要 HEROKU,我不知道为什么
git push heroku master - 还没有完成
非常感谢您的帮助
谢谢 P
更新
我已经通过链接https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#dp 在我的 c# web api 上启用了 CORS
我关注的部分是CORS with default policy and middleware
我的代码如下
我尝试过options.AddPolicy 和options.AddDefaultPolicy,但是当我从 react 应用程序调用时它仍然不起作用
namespace React_NalONE_API
{
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/*",
// "https://localhost/*");
// });
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost/*",
"https://localhost/*");
});
});
services.AddControllers();
}
// 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();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
});
}
}
}
【问题讨论】:
-
如果 Web API 在 localhost 上,您可以通过从 API 响应中添加适当的标头来修改它。如果您对
OPTIONS方法的响应缺少Access-Control-Allow-Origin,则尤其会发生这种情况,其中标头值需要是*(如果不使用凭据)或请求来源(由请求Origin标头指定)。
标签: javascript c# reactjs asp.net-web-api asp.net-core-webapi