skip to Main Content
  • I have a server written in PHP and it have some routes
  • The routes work fine with postman
  • But when I use React with Axios it gives error
  • Here is the PHP code
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET,POST,DELETE,OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

and here is how I make request with Postman
This is my raw JSON data that I feed in postman

{
    "data1" : "data1"
}

This is how I make the post request with React and Axios

await axios("url", {
        data: JSON.stringify({ "data1" , "data1" }),
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });

The url is same , but it’s giving network error

I want my axios request to get completed as it get’s completed on postman

enter image description here

enter image description here

I have also tried this config but not working

<?php


// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
    // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
    //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
    header("Access-Control-Allow-Origin: *");
}

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600");    // cache for 10 minutes

if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
    
    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support

    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    //Just exit with 200 OK with the above headers for OPTIONS method
    exit(0);
}
//From here, handle the request as it is ok

2

Answers


  1. Chosen as BEST ANSWER

    OK guyz , now I understood the problem , I hosted my PHP API in 000webhost , and this host provider does not support the OPTIONS method , which is the pre-flight request method , made by browser only (not by postman) . That's why it was working in Postman but not in React.


  2. Since you’re running your code locally, try using electronjs. It solves CORS problems. And you won’t even need the axios.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search