回应客户Cors问题



我正在学习react,我目前有一个.net核心API在本地主机:7071上的visual studio中运行。

本地API没有运行cors,因为没有要求它使用cors。

使用以下方法创建一个简单的react客户端不会因为cors错误而返回数据?

我在网上尝试了很多解决方案,但都不起作用,所以我如何才能做到这一点;简单的";反应客户端工作而不生成以下错误

Access to XMLHttpRequest at 'http://localhost:7071/api/Users' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.


function GetApiResults(){
const axios = require('axios').default;
axios.defaults.headers.common["Access-Control-Allow-Origin"] = "*";

axios({
method: 'get',
headers: { 'Content-Type': 'application/json' },
url: 'http://localhost:7071/api/Users',
}).then(function (response) {
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});

}
export default GetResults;

您对该问题有一个非常直接的描述,浏览器希望您正在使用的外部资源(在您的情况下是API,外部资源不在同一端口上(提供CORS头。如果没有设置,浏览器将不会执行请求。如果您在浏览器选项卡中打开资源URL,它将执行请求,但如果您在localhost:3000上,则此页面向不在localhost:300上的任何内容发起的任何请求都需要设置CORS。

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

浏览器安全性可防止网页向与提供网页的域不同的域发出请求。这种限制被称为同源政策。同源策略可防止恶意站点从其他站点读取敏感数据。

因此,要么在后端启用CORS支持,要么使用名为Proxy的CRA功能:https://create-react-app.dev/docs/proxying-api-requests-in-development/

我更喜欢本文末尾的手动代理配置。

重要提示:此代理仅用于发展!

这是一个循序渐进的说明,刚刚测试:

  1. 安装npm install http-proxy-middleware --save

  2. 添加内容为的src/setupProxy.js

const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
"/api",
createProxyMiddleware({
// I have a different port and Visual Studio might randomly change it
// Fix: edit running configuration 
// https://stackoverflow.com/questions/70332897/how-to-change-default-port-no-of-my-net-core-6-api
// Notice: no /api at the end of URL, it will be added.
// more details at: https://www.npmjs.com/package/http-proxy-middleware
target: "https://localhost:7002",
changeOrigin: true,
// Im using .net core 6 starting api template
// which is running with a self-signed ssl cert with https enabled
secure: false 
})
);
};
  1. 修改AXIOS配置对象以使用新的URL:
function GetApiResults() {
const axios = require("axios").default;
axios({
method: "get",
headers: { "Content-Type": "application/json" },
url: "/api/WeatherForecast"
})
/* ... */
}

注意:我使用默认的web api项目,只更改了Controller的[Route("api/[controller]")](添加了api/(。

  1. 重新启动应用程序并查看npm start输出的日志,代理可以在那里记录一些错误

CORS是一个浏览器功能。因此,您用于访问React应用程序的浏览器必须要求您使用CORS。您需要在后端设置CORS,并允许从远程源进行连接。

如果在服务器端添加CORS启用代码,效果会很好。如果你的服务器端应用程序在ExpressJS中,那么在下面添加中间件-

var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
//  res.header("Access-Control-Allow-Origin", "http://localhost:3000"); or add your react app url.
next();
});

最新更新