问题描述
我正在创建一个 React 应用程序,它托管在 localhost:3000 上。我想从 localhost:5001 上托管的 .NET Core 应用程序中获取数据。我正在使用 axios 库来发出 http 请求。
我提出请求的函数是:
async componentDidMount() {
const data = await axios.get("http://localhost:5001/api/gateways");
console.log(data);
}
我尝试使用 Postman 测试 API 并且它有效,并且从浏览器访问它并且它也有效。
同时,我尝试使用另一个 API 中的数据,这次它托管在在线服务器上,并且运行良好,这意味着问题必须出在本地主机上托管的两个应用程序之间。
解决方法
我通过向 .NET CORE 应用程序中的 HTTP 响应添加 Access-Control-Allow-Credentials 标头来解决此问题。此标头告诉浏览器服务器允许跨域请求的凭据。
它有必要修改 Startup.cs 文件中的 Configure 方法,添加以下代码:
app.Use(async (context,next) =>
{
context.Response.Headers.Add("Access-Control-Allow-Origin","*");
await next.Invoke();
});
而且,还需要修改 ConfigureServices 方法:
services.AddCors(c =>
{
c.AddDefaultPolicy(options => options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
});