一、首先修改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();
完成