WordPress

javascript — Nie można wykonać zewnętrznego wywołania API po stronie php motywu potomnego WordPress

  • 17 kwietnia, 2024
  • 4 min read
javascript — Nie można wykonać zewnętrznego wywołania API po stronie php motywu potomnego WordPress


Edytowano 14-07-24, aby wyświetlić wywołanie zwrotne pozwolenia w interfejsie API. Edycja 2: pokazała mój błąd krytyczny

Jestem nowy w wykonywaniu wywołań API w wordpress. Muszę wykonać wywołanie interfejsu API za pośrednictwem zaplecza do interfejsu API innej firmy. Nie mogę tego zrobić za pośrednictwem interfejsu użytkownika, ponieważ robi to strona trzecia, więc pojawia się błąd CORS i zalecono wykonanie połączenia za pośrednictwem zaplecza.

Przechodzę do pliku „functions.php” motywu potomnego. I piszę ten kod:

function custom_theme_api_init() {

register_rest_route('custom-theme/v1', '/data/', array(
'methods' => 'GET',
'callback' => 'make_api_call_to_third_party',
'permission_callback' => 'custom_theme_api_permissions',    
));

}

add_action('rest_api_init', 'custom_theme_api_init');

function make_api_call_to_third_party() {
$url="
$api_key = '{my_api_key}';
    
$options = array(
    'http' => array(
        'header' => "Authorization: Bearer $api_key\r\n",
        'method' => 'GET',
    ),
);
// Create a stream context
//$context = stream_context_create($options);
// Make the HTTP GET request
//$response = file_get_contents($url, false, $context);
    
// Make the API call
$response = wp_remote_get($url, $options);
if ($response === false) {
// Handle error
return false;
}
// Process the response
$data = json_decode($response, true);
return new WP_REST_Response($data, 200);
}

i w moim interfejsie wykonuję połączenie z punktem końcowym:

<script>
    const baseURL =  ' 
    function getOrgs(){
  return fetch(`${baseURL}`)
    .then(response => response.json())
    .then(data =>{
      console.log(data)
      //return renderResults(data.results);

    })
    .catch(error => console.error('Error:', error));
}
getOrgs();
</script>

Jednak otrzymuję ten błąd:

Object
   code: "rest_no_route"
   data: {status: 404} 
   message: "No route was found matching the URL and 
             request method."
   [[Prototype]]: Object

Myślę, że mój punkt końcowy może być błędny? Nie jestem pewny. Jakieś pomysły na to, co może być problemem?

Warto przeczytać!  Przesyłanie wielu zdjęć z podpisem na froncie dla niestandardowego typu postu

Teraz także otrzymuję błąd krytyczny, który wyświetla ślad stosu:

Fatal error: Uncaught TypeError: json_decode(): Argument #1 ($json) must be of type string, array given in /home/dh_r54n9h/purgace.com/wp-content/themes/divi-child/functions.php:65

Stack Trace
1.  
json_decode(Array, true)
/home/dh_r54n9h/purgace.com/wp-content/themes/divi-child/functions.php:65
2.  
make_api_call_to_third_party(Object(WP_REST_Request))
/home/dh_r54n9h/purgace.com/wp-includes/rest-api/class-wp-rest-server.php:1230
3.  
WP_REST_Server->respond_to_request(Object(WP_REST_Request), '/custom-theme/v...', Array, NULL)
/home/dh_r54n9h/purgace.com/wp-includes/rest-api/class-wp-rest-server.php:1063
4.  
WP_REST_Server->dispatch(Object(WP_REST_Request))
/home/dh_r54n9h/purgace.com/wp-includes/rest-api/class-wp-rest-server.php:439
5.  
WP_REST_Server->serve_request('/custom-theme/v...')
/home/dh_r54n9h/purgace.com/wp-includes/rest-api.php:428
6.  
rest_api_loaded(Object(WP))
/home/dh_r54n9h/purgace.com/wp-includes/class-wp-hook.php:324
7.  
WP_Hook->apply_filters(NULL, Array)
/home/dh_r54n9h/purgace.com/wp-includes/class-wp-hook.php:348
8.  
WP_Hook->do_action(Array)
/home/dh_r54n9h/purgace.com/wp-includes/plugin.php:565
9.  
do_action_ref_array('parse_request', Array)
/home/dh_r54n9h/purgace.com/wp-includes/class-wp.php:418
10. 
WP->parse_request('')
/home/dh_r54n9h/purgace.com/wp-includes/class-wp.php:813
11. 
WP->main('')
/home/dh_r54n9h/purgace.com/wp-includes/functions.php:1336
12. 
wp()
/home/dh_r54n9h/purgace.com/wp-blog-header.php:16
13. 
require('/home/dh_r54n9h...')
/home/dh_r54n9h/purgace.com/index.php:17
14. 
{main}
thrown in /home/dh_r54n9h/purgace.com/wp-content/themes/divi-child/functions.php on line 65

Każda pomoc jest doceniana. Z góry dziękuję! Miłego kodowania 🙂


Źródło