Nginx+ThinkPHP+Vue解决跨域问题的方法详解

解决过程主要有两个步骤。

1.nginx配置允许跨域

在你部署的网站对应的端口配置文件里设置,我的目录结构是这样的:

server {

listen 8080;

server_name localhost;

root "D:/phpstudy_pro/WWW/admin/landpage_server/public";

location / {

index index.php index.html error/index.html;

error_page 400 /error/400.html;

error_page 403 /error/403.html;

error_page 404 /error/404.html;

error_page 500 /error/500.html;

error_page 501 /error/501.html;

error_page 502 /error/502.html;

error_page 503 /error/503.html;

error_page 504 /error/504.html;

error_page 505 /error/505.html;

error_page 506 /error/506.html;

error_page 507 /error/507.html;

error_page 509 /error/509.html;

error_page 510 /error/510.html;

include D:/phpstudy_pro/WWW/admin/landpage_server/public/nginx.htaccess;

autoindex off;

}

location ~ \.php(.*)$ {

fastcgi_pass 127.0.0.1:9002;

fastcgi_index index.php;

fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;

fastcgi_param SCRIPT_FILENAME document_rootfastcgi_script_name;

fastcgi_param PATH_INFO $fastcgi_path_info;

fastcgi_param PATH_TRANSLATED document_rootfastcgi_path_info;

include fastcgi_params;

}

添加跨域配置

location / {

add_header 'Access-Control-Allow-Origin' '*';

add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

if ($request_method = 'OPTIONS') {

add_header 'Access-Control-Allow-Origin' '*';

add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';

add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

add_header 'Access-Control-Max-Age' 1728000;

add_header 'Content-Type' 'text/plain charset=UTF-8';

add_header 'Content-Length' 0;

return 204;

}

}

}

不过这有个坏处,就是每次你重启的时候就会被默认配置覆盖。所以这里有第二种办法:

或者在你的ThinkPHP项目的 nginx.htaccess 文件里配置。(我通过小皮将网站部署后会自动生成这个文件),上面那个文件会把这个配置文件引入进来。 include D:/phpstudy_pro/WWW/admin/landpage_server/public/nginx.htaccess;

复制代码
#伪静态配置
location / {
    index  index.html index.htm index.php;
    autoindex  off;
    if (!-e $request_filename) {
        rewrite  ^(.*)$  /index.php?s=/$1  last;
        break;
    } 
}


 # 添加跨域配置
        location / {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }
 }

|----------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | worker_processes 1; events { ``worker_connections 1024; } http { ``include mime.types; ``default_type application``/octet-stream``; ``sendfile on; ``server { ``listen 80; ``# 域名 ``server_name localhost; ``# 服务器根目录 ``root H:\php\project\UserManager\public; ``# 默认读取的文件 ``index index.php index.html index.htm; ``location / { ``# 允许浏览器跨域请求 ``if ($request_method = ``'OPTIONS'``) { ``add_header Access-Control-Allow-Origin ``'*'``; ``add_header Access-Control-Allow-Headers ``'*'``; ``add_header Access-Control-Allow-Methods ``'*'``; ``add_header Access-Control-Allow-Credentials ``'true'``; ``return 204; ``} ``if (!-e $request_filename) { ``rewrite ^(.*)$ ``/index``.php?s=/$1 last; ``break``; ``} ``try_files $uri $uri/ ``/index``.php?$query_string; ``} ``# 监听127.0.0.1:9000端口,要和php-cgi.exe配置的ip:端口一致 ``location ~ \.php$ { ``fastcgi_pass 127.0.0.1:9000; ``include fastcgi_params; ``fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; ``} ``} } |

其中的"允许浏览器跨域请求"是关键点,因为浏览器在发现网页请求是跨域请求时,会再发送一个OPTIONS请求,只有这个请求成功了才会允许跨域请求,此时,要强行配置允许跨域。(这里配置的是允许全部请求跨域)

2.在ThinkPHP中允许跨域

编辑middleware.php文件

|-------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | <?php // 全局中间件定义文件 return [ ``//允许跨域 ``//\think\middleware\AllowCrossDomain::class ``\app\middleware\AllowCrossDomain::``class ``// 全局请求缓存 ``// \think\middleware\CheckRequestCache::class, ``// 多语言加载 ``// \think\middleware\LoadLangPack::class, ``// Session初始化 ``// \think\middleware\SessionInit::class ]; |

|----------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <?php declare (strict_types = 1); namespace app\middleware; use Closure; use think\Config; use think\Request; use think\Response; /** ``* 跨域请求支持 ``*/ class AllowCrossDomain { ``protected $cookieDomain``; ``protected $header = [ ``'Access-Control-Allow-Credentials' => ``'true'``, ``'Access-Control-Max-Age' => 1800, ``'Access-Control-Allow-Methods' => ``'GET, POST, PATCH, PUT, DELETE, OPTIONS'``, ``'Access-Control-Allow-Headers' => ``'Token, Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With'``, ``]; ``public function __construct(Config ``$config``) ``{ ``$this``->cookieDomain = ``$config``->get(``'cookie.domain'``, ``''``); ``} ``/** ``* 允许跨域请求 ``* @access public ``* @param Request $request ``* @param Closure $next ``* @param array $header ``* @return Response ``*/ ``public function handle(``$request``, Closure ``$next``, ? ``array $header = []) ``{ ``$header = !``empty``(``$header``) ? ``array_merge``(``$this``->header, ``$header``) : ``$this``->header; ``if (!isset(``$header``[``'Access-Control-Allow-Origin'``])) { ``$origin = ``$request``->header(``'origin'``); ``if (``$origin && (``'' == ``$this``->cookieDomain || ``strpos``(``$origin``, ``$this``->cookieDomain))) { ``$header``[``'Access-Control-Allow-Origin'``] = ``$origin``; ``} ``else { ``$header``[``'Access-Control-Allow-Origin'``] = ``'*'``; ``} ``} ``return $next``(``$request``)->header(``$header``); ``} } |

到此这篇关于Nginx+ThinkPHP+Vue解决跨域问题的方法详解的文章就介绍到这了,更多相关Nginx ThinkPHP解决跨域内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家

相关推荐
松仔log13 小时前
Java中级——组合和继承
android·java·开发语言
我命由我1234516 小时前
Jetpack Compose - MaterialExpressiveTheme 与 MaterialTheme、ColorScheme
android·java·开发语言·java-ee·kotlin·android jetpack·android runtime
lilian23317 小时前
Harmony os 技术实战|拼豆制图06:收藏 ID、生成记录与重启恢复怎么不打架
android·java·数据库·harmonyos
2601_9557596217 小时前
ClaudeAPI成本中心与业务标签设计指南
android·java·数据库
余衫马17 小时前
2026最新版!Android Studio 极速安装与配置指南
android·ide·android studio
AFinalStone18 小时前
Android 7系统异常问题排查(五)Framework层(下)—System Server崩溃
android·tombstone·系统异常
AFinalStone18 小时前
Android 7系统异常问题排查(八)系统追踪—Trace机制与性能诊断
android·系统异常
极客猴子21 小时前
Android录音转写频繁卡顿?多款APP长时间会议场景稳定性实测
android·人工智能·智能手机·飞书
Kapaseker21 小时前
Boolean 变量到底该怎么命名?
android·kotlin
AFinalStone21 小时前
Android 7系统异常问题排查(六)应用异常(上)—ANR机制全解
android·系统异常