Search code examples
phpjsonaxiospostmanx-www-form-urlencoded

Can't read data in Postman, but works when using axios


Currently building a restful API just to practice, but one thing I've noticed is that depending on how I read it, it'll either throw errors, give no results or actually work. Frontend is React using the axios library to make requests. Backend is just plain PHP.

I have two ways of reading,

  1. file_get_contents("php://input") When I make a request from the frontend, I'm able to read the formdata and use it. However when I send in Postman it returns nothing. People recommended using x-www-form-urlencoded and so I tried it, but the result is the same. Someone else recommended reading with the superglobals

  2. $_POST['item'] In postman it's able to read the data no problem, but if I send with axios, it throws an undefinded array key warning.

I'd like to be able to test the api as I build it using Postman without having to change it later on when I incorporate it within the actual app. Clueless from this point on so any suggestions would be helpful. Apologies if I'm doing something stupid

Axios part :

let fdata = {
  email: "testemail",
  achternaam: "testachternaam",
};

axios
  .post("http://localhost/api/test", fdata)
  .then((result)=>{
    console.log(result.data)
})

PHP Part

header('Access-Control-Allow-Origin: *');
header("Access-Contro-Allow-Headers: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers,Authorization ,X-Requested-With");
header('Content-Type: application/json; charset=utf-8');

print_r($data json_decode(file_get_contents("php://input"))); // this works in with axios, but doesn't work with postman

echo $email = $_POST['email'];
// works in postman, but not with axios

In Postman I send the exact same in formdata and also x-www-form-urlencoded

Postman Request


Solution

  • Axios automatically converts data you pass into .post() into JSON format (see https://axios-http.com/docs/post_example). By contrast, your PostMan request sends form-url-encoded data (where the keys and values are encoded in key-value tuples separated by &, with a = between the key and the value, e.g. email=testemail&achternaam=testachternaam).

    These are different formats, and PHP reads them in different ways. json_decode can't work on non-JSON data, but conversely only form-encoded data is added to $_POST automatically.

    To send equivalent data from Postman, to be the same as your Axios request, change the format to "raw" and then paste

    {
      "email": "testemail",
      "achternaam": "testachternaam",
    }
    

    in there, and select JSON as the format.