I'm trying to send a post request to a locally hosted app that generates critical CSS. Here is the code I'm using.
$url = 'http://localhost:4000/';
$urls->urls = '';
$data = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($urls),
'method' => 'POST',
'data_format' => 'body',
));
It returns this error: SyntaxError: Unexpected token u in JSON at position 0.
Here is a working example in Postman. Any idea on why my code isn't working?
I'm trying to send a post request to a locally hosted app that generates critical CSS. Here is the code I'm using.
$url = 'http://localhost:4000/';
$urls->urls = 'https://www.domain.com';
$data = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($urls),
'method' => 'POST',
'data_format' => 'body',
));
It returns this error: SyntaxError: Unexpected token u in JSON at position 0.
Here is a working example in Postman. Any idea on why my code isn't working?
Here is a working example:
$body = [
'foo' => 'value1',
'bar' => 'value2'
];
$response = wp_remote_post('http://example.com', [
'data_format' => 'body',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
'body' => json_encode($body),
]);
problem coming due to how you are constructing the data object and the issue with how you're initializing $urls. Instead of using ->, you should use an associative array.
replace line in your code $urls->urls = 'https://www.domain.com';
to $urls = array('urls' => 'https://www.domain.com');
$url = 'http://localhost:4000/';
$urls = array('urls' => 'https://www.domain.com'); // Corrected initialization
$data = wp_remote_post($url, array(
'headers' => array('Content-Type' => 'application/json; charset=utf-8'),
'body' => json_encode($urls),
'method' => 'POST',
'data_format' => 'body',
));