0

If I don't use Headers and POST fields, the current request successfully handling. But, If I try send POST fields and use the Content-Type: application/json header.

That doesn't work.

I getting the CORS Error when use that. How can I solve that?

My codes:

page.js (The currently codes here)

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

// Components :: Layouts
import Header from '../layouts/header.js';
import Footer from '../layouts/footer.js';

// Components :: HTML Component
import Loading from '../assets/img/loading.svg';

class Page extends React.Component
{

    constructor(props)
    {
      super(props);

      this.loadPage = this.loadPage.bind(this);

      this.state = {
        content: null,
        loading: 'loadingArea'
      }
    }

    loadPage(page_slug)
    {

      var data = {
        slug: "hello",
      }

      var postData = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      };

      fetch('http://localhost', postData)
      .then((response) => response.json())
      .then((responseJson) =>
      {

          this.setState({
            content: responseJson,
            loading: 'loadingArea d-none',
          });

      })
      .catch((error) =>
      {
        console.error(error);
      });
    }

    render()
    {

      const page_slug = this.props.match.params.page;
      this.loadPage(page_slug);

      return (
        <div className="index">
          <Header/>
          <div className={this.state.loading}>
            <img src={Loading}/>
          </div>
          {this.state.content}
          <Footer/>
        </div>
      );

    }

}

export default Page;

And the PHP API file (requested file):

<?php

header('Content-Type: application/json');

ob_start();
print_r($_POST);
$e = ob_get_clean();

echo json_encode([$e]);
  • Add CORS support for your PHP, probably looke here: https://stackoverflow.com/questions/8719276/cross-origin-request-headerscors-with-php-headers – Daniel Z. Oct 20 '21 at 21:59

0 Answers0