PHP code implements CORS cross-domain processing of response results of Baidu Wenxin Yiyan API interface
In Web development, cross-Origin Resource Sharing ) is a common question. When we request resources under one domain name from a web page under another domain name, if cross-domain processing is not performed, the browser will block the request by default. In actual development, we often need to call third-party interfaces in the front-end page to obtain data. This article will introduce how to use PHP code to implement CORS cross-domain processing of the response results of Baidu Wenxinyiyan API interface.
The Baidu Wenxin Yiyan API interface is an interface that provides random sentences. We can obtain a random Wenxin Yiyan by sending a GET request to the interface. First, we need to use XMLHttpRequest or Fetch API in the front-end page to send a GET request to the Baidu Wenxin Yiyan API interface. Due to the browser's same-origin policy, we need to perform CORS cross-domain processing on the server side.
The following is a simple PHP code example that demonstrates how to implement CORS cross-domain processing of the response results of Baidu Wenxin Yiyan API interface:
In the above code, we first Define the address of Baidu Wenxin Yiyan API interface, and then use CURL to send a GET request to the interface. The Origin field is set in the request header, and its value is the domain name where our front-end page is located. Next, we read the data from the API response and output it. Finally, set the Access-Control-Allow-Origin field in the response header to the domain name of our front-end page to allow cross-domain access.
It should be noted that in the above code, we set the values of the Origin field and the Access-Control-Allow-Origin field to the domain name where our front-end page is located. You need to replace "https://your-domain.com" in the code with your actual domain name.
Through the above code example, we can implement CORS cross-domain processing of the response results of Baidu Wenxinyiyan API interface on the PHP server side. In this way, we can call this interface in the front-end page to obtain the data of random sentences. Everyone can make corresponding modifications and expansions according to their actual needs.
Summary:
This article demonstrates how to implement CORS cross-domain processing of the response results of Baidu Wenxinyiyan API interface through PHP code examples. In actual development, for cross-domain issues, we need to handle them on the server side to ensure that the front-end page can normally obtain data from the third-party interface. I hope this article can help everyone solve the problem of cross-domain requests.
The above is the detailed content of PHP code implements CORS cross-domain processing of response results of Baidu Wenxinyiyan API interface. For more information, please follow other related articles on the PHP Chinese website!