在 Wordpress 中向外部 API 发出 POST 请求

时间:2021-04-15 07:25:41

标签: wordpress laravel api post request

我正在尝试使用 Wordpress(也在本地主机中)向位于我的本地主机中的 API 发出 POST 请求。如果我在 Postman 中尝试 body 一切正常,但在 Wordpress 中我收到此错误:

Response:
Array
(
    [headers] => Requests_Utility_CaseInsensitiveDictionary Object
        (
            [data:protected] => Array
                (
                    [host] => localhost:8000
                    [date] => Array
                        (
                            [0] => Thu, 15 Apr 2021 07:19:50 GMT
                            [1] => Thu, 15 Apr 2021 07:19:50 GMT
                        )

                    [x-powered-by] => PHP/7.3.24-(to be removed in future macOS)
                    [cache-control] => no-cache, private
                    [content-type] => application/json
                    [x-ratelimit-limit] => 60
                    [x-ratelimit-remaining] => 59
                    [access-control-allow-origin] => *
                )

        )

    [body] => {
    "message": "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'type' cannot be null (SQL: insert into `items` (`type`, `name`, `date`, `description`, `poster`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, 2021-04-15 07:19:50, 2021-04-15 07:19:50))",

这是请求:

$url = 'http://localhost:8000/api/item/store';

$item = array(
  "type"=>"type",
  "name"=>"blablabla",
  "description"=>"blablabla",
  "date"=>"2021-05-14",
  "poster"=>"poster"
);

$args = array(
    'headers' => array(
        'Content-Type' => 'application/json'
    ),
    'body'=> wp_json_encode($item),
    );

$response = wp_remote_post($url, $args);
 
if ( is_wp_error( $response ) ) {
  $error_message = $response->get_error_message();
  echo "Something went wrong: $error_message";
} else {
  echo 'Response:<pre>';
  print_r( $response );
  echo '</pre>';
}

1 个答案:

答案 0 :(得分:0)

通过编辑 $item 传入 body 解决。我没有以正确的格式发送它

$item = array("item"=>[
  "type"=>"sport",
  "name"=>"funziona",
  "description"=>"film di prova harcoded",
  "date"=>"2021-05-14",
  "poster"=>"poster"
]);