3

I have a Laravel sever serving an api at http://localhost:8000/api/v1_0/login.

This API when hit from the web page (a login form) works fine with 200 OK status, however when I try to hit the same API with Postman, it returns me 404. I'm sure that my headers and URL spellings are correct. Is this a bug? what else could be the reason?

Vishal Sharma
  • 2,550
  • 1
  • 23
  • 40

2 Answers2

3

Just in case someone still need an answer for this. I checked the answer posted by @ZI3n but the solution didn't worked for me.

Postman was receiving a String text\html which is a default Content-Type so I suspected the code I used to processed the JSON was, somehow, forming a string not recognized by Postman as a JSON. But when was received I could see it as JSON, if changed the body type to JSON.

Because of this the request was being received as JSON formatted text but was not recognized as a JSON content, and since I was expecting a JSON the status code was ignored and replaced with 404 Not Found. Not sure if this was by the server or Postman.

So I visited the URL directly on the browser, and it was obvious that the JSON was displayed but still read as text/html and not as application/json

The next step was to refactor the code again, this time I reprocessed the JSON string by assigning the string to a variable $json as follow:

//assigning previous json string to $json
$json = $originalEchoedJsonString;

//reprocessing the string a converting it back to object
$newJson = json_decode($json);

//preparing to be send

//if PHP version 5.4+
http_response_code(200);

// Any PHP version specially 5.3 and under
header('HTTP/1.1 200 Ok', true, 200);

header('Content-type: application/json; charset=UTF-8;');

//echoing JSON back with json_encode();
echo json_encode($newJson);

After doing this I sent the request with Postman again and voila, I got a 200 Ok status and the string was properly displayed as a JSON file. Also was recognized by the browser JSON formatter as a JSON.

raphie
  • 3,285
  • 2
  • 29
  • 26
  • 2
    I was having the same issue with my NodeJS/Express backend and this solved it: Just had to add the "Content-Type" header as "application/json" as a response header along with the CORS ones.. – tamanakid Jun 20 '20 at 15:46
0

I know this is a very old question, but for future people with this problem I'll add this.

On the Headers tab, there is a Host header option. If it is not checked then the server may not accept the request and return an error. In my case a 404 rather than the 400 shown in the postman tooltip below.

Curl and browsers do add it automatically, which is why they can behave differently when this option is not checked.

Postman Host Header

Dharman
  • 30,962
  • 25
  • 85
  • 135
Charlie G
  • 538
  • 5
  • 14