Implementation of cors request in fetch in react, reactcors
React is used in the project, and fetch must be used to replace ajax.
Because the create_react_app tool of react is very convenient, it is basically out-of-the-box. After creating a project and entering the npm start command, it automatically listens to a port of 3000, and the front-end part is ready.
Reference: https://github.com/facebookincubator/create-react-app
I used phalcon In the backend.
Due to the front-end and back-end separation, I tried to make it the same domain in nginx (the top-level domain names of the front-end and back-end APIs are the same) for convenience. However, when the phalcon framework is single-entry and react listening 3000, through nginx reverse proxy, JavaScript cannot be found, so I gave up my intention to share the same domain.
Therefore, I configured two domain names:
1. www.xxx.com
2. data.xxx.com
The first domain name is used in the react part, and the port number is 3000 (for debugging, the official launch is 80)
The second domain name is used for api, and the port number is 80.
As a result, a cross-origin problem occurs.
Cors detailed introduction please see: http://www.bkjia.com/article/102694.htm
The following are settings for allowing cross-domain name access in php.
$origin = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:''; $allowOrigin = [ 'http://www.xxx.com', 'http://xxx.com' ]; if (in_array($origin, $allowOrigin)) { header('Access-Control-Allow-Origin: ' . $origin); } header('Access-Control-Allow-Methods: PUT,POST,GET,DELETE,OPTIONS'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Headers: Content-Type, Accept');
The following are ajax requests for fetch.
let postData = {a:'b'};fetch('http://data.xxx.com/Admin/Login/login', { method: 'POST', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: JSON.stringify(postData)}).then(function(response) { console.log(response);});
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.