Ad

React.js + PHP/Apache: Request Header Field Content-type Is Not Allowed By Access-Control-Allow-Headers In Preflight Response

- 1 answer

I want to create a contact page in React.js. After clicking on the submit button, a PHP page (on Apache) is called using the fetch method (using POST). Unfortunately, I keep receiving the following errors (both on my localhost:3000/dev machine and on an Apache server:

Access to fetch at 'http://example.com/dir/email.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

This is the sendEmail function that is called on submission:

  sendEmail() {
    fetch('http://example.com/dir/email.php', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        'firstname': this.state.firstName,
        'lastname': this.state.lastName,
        'message': this.state.message
      })
    }).then(function(response) {
      console.log(response);
      return response.json();
    }).then(function (json) {
      console.log(json);
    });
  }

My PHP script now looks like this (I don't have any logic for now):

<?php
  header('Access-Control-Allow-Origin: *');
  header('Access-Control-Allow-Methods: GET, POST');
  header("Access-Control-Allow-Headers: X-Requested-With");

  echo json_encode(array('success' => true));

I also tried adding a .htaccess file, with the following content, but that didn't seem to work either:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Content-Type "*"
    Header set Access-Control-Accept "*"
    Header set Access-Control-Allow-Methods "GET, POST"
    Header set Access-Control-Allow-Headers: X-Custom-Header
</IfModule>

I think the problem should be on the server, since all examples I found on fetch are looking like mine. I searched for this problem, but the answers I found didn't work or are for Express servers instead.

Maybe there are other, better ways to create a simple contact form like this in React.js, so I'm open for suggestions. I'm quite new with React.js, so there's a big chance I'm missing something obvious...

Any input will be very much appreciated!

Ad

Answer

Before making a CORS request (that's it, a AJAX/JSON/HTTP request which domain name is not the same as the domain of the html), the browser will send a 'pre-flight request' with method OPTIONS.

Reference: https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request

So, put this on your php file:

<?php
// CORS support
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");

// https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
if($_SERVER["REQUEST_METHOD"] == "OPTIONS") exit();
// before sending CORS request, modern browsers often make "pre-flight request" in order to see which headers are allowed/accepted from custom origin
// that request must be answered with status code 200 OK, and must contain header Acces-Control-Allow-Headers

Explanation:

  • The preflight request is intended to make sure that the server understood that the request is a CORS request.
  • The "Access-Control-Allow-Header" lists all HTTP headers that can be used on following CORS request

More detailed explanation can be read at referenced link above

Ad
source: stackoverflow.com
Ad