解决过程主要有两个步骤。
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:\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文件
<?php
// 全局中间件定义文件
return [
//允许跨域
//\think\middleware\allowcrossdomain::class
\app\middleware\allowcrossdomain::class
// 全局请求缓存
// \think\middleware\checkrequestcache::class,
// 多语言加载
// \think\middleware\loadlangpack::class,
// session初始化
// \think\middleware\sessioninit::class
];<?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解决跨域内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论