Home >PHP Framework >ThinkPHP >How thinkphp completes cross-domain requests
1. Header class
In the thinkphp framework, you can use the Header class to set the response header to realize the function of cross-domain requests. The specific method is to add the following code to the controller method:
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
Among them, the first line of code indicates that cross-domain requests from all sources are allowed, or it can be set to a specific source; the second line of code indicates that cross-domain requests are allowed Request header information carried by the request. After setting this up, you can implement basic cross-domain requests.
2. Third-party libraries
In addition to using the Header class to set up cross-domain requests, you can also use third-party libraries to simplify this process. The following takes the mainstream CORS (Cross-Origin Resource Sharing) library cors extension as an example to introduce how to use a third-party library to implement cross-domain requests.
Install cors extension
Open the command line window and execute the following command:
composer require topthink/think-cors
Configuration cors expansion
In the project's config folder, create a cors.php file and enter the following code:
<?php return [ // 允许的请求域名 'allow_origin' => ['*'], // 允许的请求头信息 'allow_headers' => 'Origin, X-Requested-With, Content-Type, Accept', // 允许的请求方法 'allow_methods' => 'GET, POST, PUT, DELETE, PATCH', // 是否允许发送cookie 'allow_credentials' => true, // 跨域请求缓存时间 'max_age' => 3600, ];
Among them, $allow\_origin represents the allowed request Domain name, can be set to a specific domain name, or can be set to the wildcard "*"; $allow\_headers represents the allowed request header information, $allow\_methods represents the allowed request methods, $allow\_credentials represents whether sending cookies is allowed, $ max\_age represents the cross-domain request cache time.
Modify the configuration file
In the config folder of the project, find the app.php file, the configuration is as follows:
return [ // ... 'middleware' => [ // ... \think\middleware\Cors::class, ], ];
Call cors extension
In the controller method that requires cross-domain requests, you can directly call the method in cors extension to realize the setting of cross-domain requests:
use think\facade\Cors; public function index() { Cors::allowAllOrigin(); return json(['code' => 200, 'msg' => 'success']); }
After setting this, cross-domain requests can be implemented.
The above is the detailed content of How thinkphp completes cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!