Nginx+ThinkPHP+Vue解决跨域问题的方法详解
解决过程主要有两个步骤。
1.nginx配置允许跨域
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:phpprojectUserManagerpublic;
# 默认读取的文件
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文件
'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解决跨域内容请搜索科站长以前的文章或继续浏览下面的相关文章希望大家以后多多支持科站长!
上一篇:PHP三种方式读取RSA密钥加解密、签名验签完整教程
栏 目:PHP编程
本文标题:Nginx+ThinkPHP+Vue解决跨域问题的方法详解
本文地址:https://fushidao.cc/wangluobiancheng/3404.html
您可能感兴趣的文章
- 05-12php编程基础期末考试重点是什么,php编程基础
- 05-12PHP是前端还是后端语言?PHP前端编程语言常被误解为纯后端
- 05-12{php 5 高级编程}怎么样,php5高级编程教程
- 05-12php编程windows环境怎么配置?PHP Windows环境配置教程
- 05-12php编程无限保存,php如何实现无限级数据保存
- 05-12php编程宝典dvd哪里下载,php编程宝典
- 05-12php编程能力提升难吗,php编程能力提升
- 05-12php需要怎么编程,php编程入门教程
- 05-12如何高效学习PHP编程?PHP实战技巧有哪些
- 05-12php编程的软件有哪些,php编程软件推荐
阅读排行
推荐教程
- 07-25PHP建立MySQL与MySQLi持久化连接(长连接)区别
- 07-25PHP WindSearch实现站内搜索功能
- 07-25PHP调用FFmpeg实现视频切片
- 02-01PHP编程用什么软件?资深开发者为你揭秘最佳工具组合
- 01-23重庆哪里能找到专业的PHP编程培训班?推荐哪家比较好?
- 01-23如何通过PHP编程实现从文本框输入并处理整数的完整代码示例?
- 02-22PHP编程架构原理,如何深入理解其应用与实际开发中的应用场景?
- 01-28php编程第3版pdf中,有哪些新特性或更新让我不得不重新学习?
- 01-21PHP编程如何巧妙实现九九乘法表?分享编程技巧与代码细节!
- 11-23PHP 7安装使用体验之性能大提升,兼容性强,扩展支
