【发布时间】:2021-07-31 09:23:02
【问题描述】:
我将 Visual Studio 代码与 liveserver 一起用于 html/javascript,并将 VS Studio 2019 用于 Dot net core Web API 我已经在 Windows 10 本地的 IIS 中为 web api 创建了站点。
- 我有一个登录页面,接受用户 ID 和密码。 这是在 login.html 中编码的
登录页面有以下javascript函数,在登录按钮点击事件时调用
function fnlogin() {
window.location.href = "http://localhost:5500/productmenu.html"
}
- 登录后,会显示一个菜单页面。 这是在 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 中编码的
-
一旦用户输入产品代码并点击搜索,就会调用一个dot net core web api,并使用fetch api将数据显示在productinfo.html中
该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));
- dot net core web api 在 startup.cs 中有以下内容
method : configureServices
services.AddDefaultPolicy(
options.AddDefaultPolicy (
builder =>
{
builder.WithOrigins("http://127.0.0.1:5500)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
})
)};
configure方法有如下
app.UseRouting();
app.UseCors();
app.UseAuthorization():
web api 发布在 IIS 中,端口为 8082
问题如下
- 当我直接在浏览器中测试 web api 时,它可以正常工作
- 当我在实时服务器中运行 productmenu.html 时,会打开一个带有链接的新浏览器窗口 127.0.0.1:5500/productmenu.html 并显示菜单。选择“产品信息”菜单选项后,将显示页面产品信息页面。输入产品 ID 并单击搜索按钮后,将调用 Web api,然后正确显示产品信息。没问题..
- 但是当我在 VS 代码/实时服务器中运行 login.html,并使用相同的步骤(如 #2 中所述)导航到产品信息页面并单击搜索按钮时,我在 Chrome 中收到以下 CORS 错误开发工具 “访问 .. from origin ... 已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' 标头。”
我检查了 Chrome 开发工具中的网络选项卡并查看了请求标头
Accept: */*
Host: localhost:8082
Origin: http://localhost:5500
Sec-Fetch-Dest: Empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site : same-site
【问题讨论】:
标签: javascript c# asp.net-core asp.net-web-api .net-core