0

I ask for help on how to interact with ReactJS and PHP.

I have a php file to communicate with the database and get the data from the database in JSON format.


db.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);

All is well and I get this in JSON format.

Using axios, I'm processing this PHP file in ReactJS.


index.js

import React from 'react';
import ReactDOM from 'react-dom';

import registerServiceWorker from './registerServiceWorker';
import axios from "axios";


import Product from "./Product";


componentWillMount() {

axios.get('db.php')
.then(({ data }) => {
     this.setState({
         result: data
         });
     });
}

render() {
    return(
        <div className="products">
            {this.state.result.map((product, i) => (
                <Product
                    key={i}
                    title={product.post_title}
                    guid={product.post_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;

My JSON encode

[  
   {  
      "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\/",
   },
]

And I get an error in ReactJS The requested resource does not have the header "Access-Control-Allow-Origin".

In the hosts file already registered 127.0.0.1 localhost domain.com But still a mistake.

How can I solve this problem or what to write in the axios query. Help me please! Thank you

  • What is the URL of the request that you're getting the error for? – Catalyst May 14 '18 at 06:53
  • I'm referring to the url http://example.com/db.php it is on the same server. but in a different directory. I tried already to specify the proxy in package.json, add headers to php. Nothing helps! – 147armedru May 14 '18 at 08:55
  • Please add the lines from this comment: https://stackoverflow.com/a/25661403/933575 to `db.php`, and post back the results. – Catalyst May 14 '18 at 18:40

1 Answers1

0

You need to set header for allow access control and pass headers in axios. also you need to enable cors on your php server.

Example of cors implementation in php.

Alejandro
  • 5,834
  • 1
  • 19
  • 36
Dayachand Patel
  • 469
  • 4
  • 12