[英]Dot Net Core Web API with Javascript - CORS policy error
I am using Visual Studio code with liveserver for html/javascript, and using VS Studio 2019 for Dot net core Web API I have create site in IIS on Windows 10 locally for the web api.
登錄頁面有以下 javascript function,在登錄按鈕點擊事件中調用
function fnlogin() {
window.location.href = "http://localhost:5500/productmenu.html"
}
<header>
<ul class = "nav">
<li class="navlink"> <a href="productInfo.html> target="content"> Product Information <a> <li?
<li class="navlink"> <a href="orderHistory.html> target="content"> Order History <a> <li?
</ul>
</header>
用戶選擇菜單選項“產品信息”后,將顯示另一個 html 頁面 這在 productinfo.html 中編碼
Once the user enters product code and clicks on search, a dot net core web api is invoked and data is displayed in the productinfo.html using fetch api
api在JS中調用如下
fetch('http://localhost:8082/api/product/' + productId)
.then(response => response(json))
.then((response => {
return response
})
.then ( (response) => {
console.log(response);
})
.catch(err => console.log(err));
method : configureServices
services.AddDefaultPolicy(
options.AddDefaultPolicy (
builder =>
{
builder.WithOrigins("http://127.0.0.1:5500)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
})
)};
配置方法有以下
app.UseRouting();
app.UseCors();
app.UseAuthorization():
web api 發布在 IIS 現場,端口為 8082
問題如下
我檢查了 Chrome 開發工具中的網絡選項卡並查看請求標頭
Accept: */*
Host: localhost:8082
Origin: http://localhost:5500
Sec-Fetch-Dest: Empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site : same-site
您在 Cors 語法中有一個錯誤。 這是默認策略的語法:
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://127.0.0.1:5500")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
但如果它仍然不起作用,您可以嘗試用命名策略替換默認的 Cors 策略
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("AllowOrigins", builder =>
{
builder.WithOrigins("http://localhost:5500")
.AllowAnyMethod()
.AllowAnyHeader();
}));
.....
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.....
app.UseRouting();
app.UseCors("AllowOrigins");
app.UseAuthorization();
....
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.