我正在 React Web 应用程序中使用 Fetch 进行 API 调用(在另一个域上运行)。我收到错误以下错误。
从源“http://localhost:3000”获取“--------API URL---------”的访问已被 CORS 策略阻止:
对预检请求的响应不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我还在 Stack Overflow 上阅读了关于同一问题的几个答案,标题为“Access-Control-Allow-Origin”,但仍然不知道如何解决这个问题。我不想在 Chrome 中使用扩展程序或使用临时黑客来解决这个问题。请提出解决上述问题的标准方法。
我的代码如下所示:
{
return fetch('-----------API URL--------',
{ method:'GET',
mode: 'cors',
headers:{
'Access-Control-Allow-Origin':'*'
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.ALLORDERSRX);
this.setState({
isLoading: false,
dataSource: responseJson.ALLORDERSRX,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
Run Code Online (Sandbox Code Playgroud) 我一直在我的网站上运行新闻 api,并通过将文件拖到网络浏览器中来在我的计算机上进行测试,网址会像这样显示file:///C:。然后我会将所有更改上传到我的 GitHub 存储库并在 Github 页面上运行它https://name.github.io/repository/。
很长一段时间一切都工作正常,但最终 API 停止工作并在控制台中显示错误Access to fetch at 'https://newsapi.org/v2/everything?xx' from origin 'https://name.github.io' 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.
我尝试添加mode: 'no-cors'到提取中,但它不起作用return response.json();
我的函数如下所示:
const url = 'https://newsapi.org/v2/everything?' +
'qInTitle=""&' +
`from=` +
'language=en&' +
'apiKey=';
const req = new Request(url); …Run Code Online (Sandbox Code Playgroud) 我的应用程序的客户端是.NET6,服务器端Web API是.NET 4.8。当尝试访问服务器端时,浏览器控制台中会产生以下错误:
从源“https://localhost:34564”获取“https://localhost:12345/api/controller/method”的访问已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头关于所请求的资源。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
在我的startup.cs中,我有以下代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors("AllowSpecificOrigin");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
}); …Run Code Online (Sandbox Code Playgroud) 我在 Cloudflare Workers 上有一个 Javascript 边缘函数。它唯一做的就是检查特定标头并返回包含相应值的 JSON
请参阅下面的代码
async function handleRequest(request) {
const url = new URL(request.url);
const psk_db = await KV_STORAGE.get(request.headers.get(PRESHARED_AUTH_HEADER_KEY));
if (psk_db === null) {
return new Response("Access denied", { status: 404 });
}
else{
//calculate number
//return JSON
const data = {
pswd: psk_db,
};
json = JSON.stringify(data, null, 2);
}
return new Response(json, {
headers: {
'content-type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': url.origin,
},
})
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
Run Code Online (Sandbox Code Playgroud)
现在,该函数在 cloudflare 测试环境中运行良好,但是当我尝试使用运行此 javascript 函数的按钮从 html 页面请求时 …
我试图通过suredbits从API获取免费的NFL数据。不幸的是,他们没有在标头中添加Access-Control-Allow-Origin,这会导致CORS问题。当我尝试运行这样的代码时...
$.getJSON("http://api.suredbits.com/nfl/v0/stats/jones/julio", function(playerData) {
alert(playerdata);
}
Run Code Online (Sandbox Code Playgroud)
我不断收到这个错误 No 'Access-Control-Allow-Origin' header is present on the requested resource.
因此,基本上,他们有什么办法可以通过客户端解决错误?