解决Nginx+ThinkPHP+VUE的跨域问题

news/2024/7/7 21:47:31 标签: nginx, vue.js, android

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

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);
    }
}

 结束。


http://www.niftyadmin.cn/n/5460245.html

相关文章

- 工程实践 - 《高并发系统正确性保障 - 锁的范式》

本文属于专栏《构建工业级QPS百万级服务》系列简介-CSDN博客 “锁”&#xff0c;在新华字段的解释是“加在门、箱子、抽屉等物体上的封缄器&#xff0c;要用专用的钥匙才能打开”。在计算机领域&#xff0c;可以抽象为&#xff1a;主体A&#xff0c;在物品W上&#xff0c;附加物…

Kaggle注册验证码问题(Captcha must be filled out.)

Kaggle注册验证码问题 Captcha must be filled out.使用Edge浏览器 Header Editor 插件安装 下载插件Header Editor 导入重定向脚本 点击扩展插件&#xff0c; 打开Header Editor插件&#xff0c;进行管理 点击导入输入下载链接进行下载或者导入本地json文件(二者任选其一…

奇偶分家 (10分)给定N个正整数,请统计奇数和偶数各有多少个?

#include <stdio.h> #include <string.h> int main() { // 输格式&#xff1a; // 输第给出个正整N&#xff08;≤1000&#xff09;&#xff1b;第2给出N个负整数&#xff0c;以空格分隔。 // // 输出格式&#xff1a; // 在中先后输出奇数的个数、偶数…

# Apache SeaTunnel 究竟是什么?

作者 | Shawn Gordon 翻译 | Debra Chen 原文链接 | What the Heck is Apache SeaTunnel? 我在2023年初开始注意到Apache SeaTunnel的相关讨论&#xff0c;一直低调地关注着。该项目始于2017年&#xff0c;最初名为Waterdrop&#xff0c;在Apache DolphinScheduler的创建者…

SpringBoot -- 错误处理机制

如果我们的项目发生了错误&#xff0c;SpringBoot会使用其错误处理机制来处理我们的错误&#xff0c;返回相对应的结果。如果我们相对其进行自定义修改&#xff0c;那么就要了解SpringBoot的错误处理机制流程&#xff0c;下面就对其进行介绍。 1. 错误处理机制流程 SpringBoo…

uniapp中怎么引入echarts(最简单)

目录 引言 echarts.vue 文件代码 echarts-config 文件代码 在需要引入echarts图表的页面(.vue)中进行导入该文件(echarts.vue) 使用该组件(echarts) 引言 在uniapp中需要引入echarts时的时候,需要引入两个配置文件.分别是 echarts.vue 以及 echarts-config 放在你项目中…

类的函数成员(一):普通构造函数

一 .概述 数据成员多为私有的&#xff0c;要对它们进行初始化&#xff0c;必须用一个公有函数来进行。同时这个函数应该在且仅在定义对象时自动执行一次。这个函数称为构造函数&#xff08;constructor&#xff09; 。 构造函数的特点如表1所示。 表1 构造函数的特点 序号特征项…

Qt 富文本处理 (字体颜色大小加粗等)

Qt中支持HTML的控件有textEdit 、label 、textBrowser 。 接口&#xff1a;setHtml("Qt"); toHtml(). 文本样式设置 : 可分字设置 &#xff0c;主要使用QTextCharFormat类进行文本样式设置。 示例&#xff1a; QTextCharFormat fmt; //粗体 fmt.setFontWeight…