php跨域代码,欣达CMS专用版
核心代码(php)
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');
header("Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,x-tag,vtoken,authKey,sessionID,osname,xindaclient");这里包括了请求头。
如果以上代码无效,那么一定是web服务器拦截了options请求,那么具体怎么处理呢?
如果IIS服务器:
1、找到IIS处理模块
2、找到OPTIONSVerbHandler直接删除,因为它直接拦截处理啦options请求
3、找到php处理模块,请求限制中加入:OPTIONS
或者直接使用下面web.config文件(注意php路径)
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <handlers> <remove name="php-7.4.3" /> <remove name="OPTIONSVerbHandler" /> <add name="php-7.4.3" path="*.php" verb="*" modules="FastCgiModule" scriptProcessor="D:\tools\7.4.3\php-cgi.exe" resourceType="Either" requireAccess="Script" /> </handlers> </system.webServer> </configuration>
如果是nginx服务器,那么在配置文件中加入以下代码:
location / {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin '*';
# Allow-Headers 指定允许的自定义请求头,如用户 Token
add_header Access-Control-Allow-Headers 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,x-tag,vtoken,authKey,sessionID';
# 经过我的实验这个可以不加(有需要另说)
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, PATCH, OPTIONS';
# 请求是否携带 Cookie,无需要可忽略。有说该设置为 true 时 Allow-Origin 不可为 '*'
add_header Access-Control-Allow-Credentials true;
# 这个响应 Content-Type 也是根据需要设置(一般情况可以不用设置)options二次请求间隔时间
add_header 'Access-Control-Max-Age' 604800;
add_header Content-Type 'text/plain; charset=utf-8';
# 如下 Content-Length 可忽略,返回状态码根据个人习惯可设置为 200,但是必不可少
add_header Content-Length 0;
return 200;
}
}上诉配置文件如果有报错,一般就是因为location /已经存在了,只需要找到,将其合并即可。如果在BT面板中,那么location /有可能会在伪静态规则里面。
经测试Apache服务器不存在上诉问题
另外需要注意的是Nginx服务器不支持静态文件POST,会出现405的提示,因此要么是请求地址上带上index.php。要么是修改Nginx的配置文件,修改方法有2种。
方法一:
在root 网站目录下加入以下代码
error_page 405 =200 @405;
location @405
{
root /www/xcwl.com;
}方法二:
在root 网站目录下加入以下代码
error_page 405 =200 http://$host$request_uri;
特别注意:不要修改405 =200 这个等号前后的空格


