Sending a post request with JSON content type

admin2025-01-08  7

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?

Share Improve this question edited Mar 19, 2022 at 5:14 228 asked Mar 18, 2022 at 22:38 228228 214 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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),
]);

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',
));
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736266975a1165.html

最新回复(0)