N
N
Narchist2018-05-14 12:47:31
PHP
Narchist, 2018-05-14 12:47:31

ReactJS + PHP + Axios - how to solve the Access-Control-Allow-Origin problem?

Good afternoon, I'm asking for help in solving the problem with CORS and 'Access-Control-Allow-Origin'. The second day nothing happens!
Application on create-react-app
I get data from the database in a PHP file and translate it into JSON format. Everything is fine. I get standard JSON
react.php

require($_SERVER['DOCUMENT_ROOT'] . '/wp-blog-header.php');

global $post;

$args = array(
    'numberposts' => '10',
    'offset' => '27',
    'post_type' => 'product',
    'post_status' => 'publish',
    'orderby' => 'menu_order',
    'order' => 'ASC'
);

$products = get_posts($args);


foreach ( $products as $product ) {
    $result = $products;
}

echo json_encode($result);

Data in the following JSON format
[  
   {  
      "ID":3431,
 "post_title":"\u041a\u041e\u041d\u0426\u0415\u041d\u0422\u0420\u0410\u0422\u041e\u0420 8\u0424-1\/2",
      "guid":"http:\/\/domain.ru\/product\/koncentrator-8f-1-buk\/",
   },
]

In ReactJS I get them with axios.get();
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import axios from "axios";

import Product from "./Product";

class App extends React.Component {
    constructor() {
        super();
        this.state = {
            result: []
        };
    }

    componentWillMount() {
        axios
            .get('http://example.com/wp-content/themes/armed/mobile/react.php')
            .then(({ data }) => {
                this.setState({
                    result: data
                });
            });
    }



    render() {
        return(
            <div className="products">
                {this.state.result.map((product, i) => (
                    <Product
                        key={i}
                        post_title={product.post_title}
                        guid={product.guid}
                    />
                ))}
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

product.js
import React from 'react';

const Product = ({post_title, guid}) => (
    <div>
        <div>{post_title}</div>
        <div>{guid}</div>
    </div>
);

export default Product;

And in the end I get an error in the browser

GET example.com/wp-content/themes/armed/mobile/react.php 404 (Not Found)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
at createError (createError.js:16)
at settle(settle.js:18)
at XMLHttpRequest.handleLoad(xhr.js:77)

I googled and read a lot.
Wrote 'proxy' in package.json - didn't help
Specified header in PHP file
header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

It didn't work either. It doesn't work
on the local server via OpenServer. It doesn't work
on the DevServer that runs webpack either. It doesn't work either
on the real server.
I understand that there are problems with accessing a different URL, on a different port. OK. Plain JSON, txt on this url doesn't work either. But, for example, this one https://5a523e6850dffb001256e0bf.mockapi.io/products - it works! And of course, if you drop the file directly into the application folder in 'src', then axios receives the file inside the application. But I really need to get the file at a different path/address/url.
How to get around this issue with request and CORS?
Maybe there are some other options for getting JSON from PHP in React?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-05-14
@Narchist

Read any recent article on REST API in PHP No one writes API like this:
To solve the problem with cors, install nginx and add a host for your project to hosts, and write a config for nginx, according to which it will redirect requests to different ports on different paths of your host.
hosts:
nginx.conf:

server {
  listen 80;
  server_name project;

  location ^~ / {
    proxy_pass http://localhost:3000/;
  }
  location ^~ /api/ {
    proxy_pass http://localhost:3001/api/;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question