Zachary Raineri
Zachary Raineri

Reputation: 146

React JS fetch as POST to cross-origin, PHP returns 200 but without body response

I know similar questions have been asked, but nothing on here as worked. Thank you in advance!

I'm using fetch from a react JavaScript app (located at http://localhost:3000) to post data too, and get a response from a local PHP API (using XAMPP and located at http://local.api.mysite.com/user)

Every-time I get a 200 status without any returned headers or body. If I go to the PHP URL in my browser it works just fine

I've ensured cors is set in both js and php, set content types, turned off caching, and tried every suggested fix on here and Google.

This is a last resort

JS:

fetch('http://local.api.mysite.com/user', {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
    },
    body: JSON.stringify(data),
    }).then(console.log(response))

PHP:

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header("Cache-Control: no-cache");
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    exit(0);
}
$output = json_encode(['status' => 'recieved']);
header('Content-Length: '.strlen($output));
header('Content-Type: application/json');
echo $output;
exit;

Previously I had limited my PHP headers to be more restrictive, but I found this code block and am using it to let anything pass for testing.

Solution Rikin's comment on his answer had me open dev tools, go to the network tab, and view the response directly. This showed a server error that was occurring and leading to the empty response with a 200 status

Upvotes: 0

Views: 2110

Answers (1)

Rikin
Rikin

Reputation: 5473

This is fetch issue on how its built. You get a stream of response which you have to either parse it as json or text or blob and then look for actual response that we expect. I modified code a bit below to get you what you need.

fetch('http://local.api.mysite.com/user', {
  method: 'POST',
  mode: 'cors',
  headers: {
    'Content-Type': 'application/json',
    'Cache-Control': 'no-cache'
  },
  body: JSON.stringify(data),
})
.then(data => data.ok && data.json())
.then(response => console.log(response));

This is what you get back in fetch response: https://developer.mozilla.org/en-US/docs/Web/API/Response

Upvotes: 1

Related Questions