thinkphp6 + nginx + antd Admin-Vue解决跨域

一、首先修改vue.config.vue

    devServer: {
        proxy: {
            '/': { //此处要与 /services/api.js 中的 API_PROXY_PREFIX 值保持一致
                target: process.env.VUE_APP_API_BASE_URL,
                changeOrigin: true,
                pathRewrite: {
                    '^/': ''
                }
            }
        }
    },
image.png

二、设置.env(正式)和.env.development(开发)中VUE_APP_API_BASE_URL的地址

VUE_APP_API_BASE_URL=http://yourUrl.com
image.png

三、serve下面的api.js修改跨域相关

我服务端是PHP,请求地址为http://yourUrl.com/categoryList

image.png


四、nginx服务器设置伪静态
Access-Control-Allow-Origin要设置具体的带端口号

location / {
if (!-e $request_filename){
rewrite ^(.*)$ /index.php?s=$1 last; break;
}
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin 'http://localhost:8080/';
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Headers 'token,Authorization';
add_header Content-Length 0;
return 204;
}
}

image.png

五、thinkphp6代码

入口文件

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Allow-Origin: http://localhost:8080");
    header("Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With, X-Token");
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH');
    exit; // 直接退出,不走后序流程
}
image.png

路由

<?php
/**
 *
 * User: 小贝壳
 **/
use think\facade\Route;

Route::post("/login", "Login/login")->middleware('allowcross');

Route::group('/', function(){
    Route::post("/categoryList", "Category/index");
})->middleware('check')->allowCrossDomain();

完成

推荐阅读更多精彩内容