Javascript 如何在 react.js 中允许 CORS?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46337471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:24:26  来源:igfitidea点击:

How to allow CORS in react.js?

javascriptajaxreactjscors

提问by Shweta Singh

I'm using Reactjs and using API through AJAX in javascript. How can we resolve this issue? Previously I used CORS tools, but now I need to enable CORS.

我正在使用 Reactjs 并通过 JavaScript 中的 AJAX 使用 API。我们如何解决这个问题?之前我使用过 CORS 工具,但现在我需要启用 CORS。

采纳答案by RGarcia

Possible repeated question from How to overcome the CORS issue in ReactJS

如何克服 ReactJS 中的 CORS 问题中可能重复的问题

CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.

CORS 通过添加新的 HTTP 标头来工作,这些标头允许服务器描述允许使用 Web 浏览器读取该信息的源集。这必须在服务器中配置以允许跨域。

You can temporary solve this issue by a chrome plugin called CORS.

您可以通过名为 CORS 的 chrome 插件临时解决此问题。

回答by Rohit Sinha

It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-

最好在服务器端添加 CORS 启用代码。要在基于 NodeJS 和 ExpressJs 的应用程序中启用 CORS,应包含以下代码-

var app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

回答by sumit

Suppose you want to hit https://yourwebsitedomain/app/getNamesfrom http://localhost:3000then just make the following changes:

假设您想从http://localhost:3000 访问https://yourwebsitedomain/app/getNames,然后只需进行以下更改:

packagae.json :

包.json :

   "name": "version-compare-app",
   "proxy": "https://yourwebsitedomain/",
   ....
   "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
     ...

In your component use it as follows:

在您的组件中按如下方式使用它:

import axios from "axios";

componentDidMount() {
const getNameUrl =
  "app/getNames";

axios.get(getChallenge).then(data => {
  console.log(data);
});

}

}

Stop your local server and re run npm start. You should be able to see the data in browser's console logged

停止本地服务器并重新运行 npm start。您应该能够看到浏览器控制台中记录的数据

回答by alireza ranjbaran

You need to activate CORS in server Side!

您需要在服务器端激活 CORS!

if you can not change the server (for example if you use external API), create a proxy server. Please check thispost for more details.

如果您无法更改服务器(例如,如果您使用外部 API),请创建一个代理服务器。请查看帖子以获取更多详细信息。