0

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?

enter image description here

2 Answers 2

0

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),
]);
0

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',
));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.