如果整个项目都需要支持跨域请求的话,可以在/config/server.php
配置文件中进行修改,相关参数如下:
return [
// +-----------------------------
// | onRequst 跨域相关
// +-----------------------------
// 接口跨域设置
'origin' => '*',
// 接口数据请求类型
'type' => '',
// 接口跨域允许请求的类型
'methods' => 'POST,GET,OPTIONS,DELETE',
// 接口是否允许发送 cookies
'credentials' => 'true',
// 接口允许自定义请求头的字段
'headers' => 'Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin, api_key',
];
如果只是某个控制器方法需要响应跨域请求的话,可以在fetch()
方法中进行设置。
$this->fetch('抛出内容', 200, [
// 接口跨域设置
'origin' => '*',
// 接口数据请求类型
'type' => '',
// 接口跨域允许请求的类型
'methods' => 'POST,GET,OPTIONS,DELETE',
// 接口是否允许发送 cookies
'credentials' => 'true',
// 接口允许自定义请求头的字段
'headers' => 'Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin, api_key',
]);