In web development, Cross-Origin Resource Sharing (CORS) is a common challenge. When a webpage requests resources from a different domain, the browser will block the request if CORS is not properly handled. This article demonstrates how to use PHP code to manage Baidu Wenxin Hitokoto API responses and enable cross-origin access from the frontend.
The Baidu Wenxin Hitokoto API provides random sentence data. Frontend pages typically use XMLHttpRequest or Fetch API to send GET requests to retrieve the data. Due to the same-origin policy, server-side CORS handling is required to access the API data correctly.
<?php // Baidu Wenxin Hitokoto API URL $url = 'https://v1.hitokoto.cn/'; // Send GET request using CURL $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set Origin header to resolve CORS issues curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Origin: https://your-domain.com', // Replace your-domain.com with your actual domain ]); $response = curl_exec($ch); curl_close($ch); // Set Access-Control-Allow-Origin header to allow cross-origin access header('Access-Control-Allow-Origin: https://your-domain.com'); // Output the API response echo $response; ?>
In this example, the Baidu Wenxin Hitokoto API URL is defined first, and a GET request is sent using CURL. The Origin header is set to the frontend domain to address CORS issues. After retrieving the API response, the Access-Control-Allow-Origin header is set to the same domain to allow cross-origin access. Make sure to replace "https://your-domain.com" with your actual domain.
With the above PHP code, the server can handle CORS for Baidu Wenxin Hitokoto API responses. Frontend pages can call the API to get random sentences, meeting practical development requirements.
This article demonstrates how to use PHP to handle cross-origin requests for Baidu Wenxin Hitokoto API. In real-world development, CORS issues usually need to be resolved on the server side to ensure frontend pages can access third-party API data properly. This guide aims to help developers implement cross-origin requests effectively.
Related Tags:
API