記:vite3+vue3+axios前端項目跨域問題解決【前端和服務器nginx配置】

前言:什么是跨域,網上一搜一大把,所以這里直接跳過,直入主題。

處理方式:不通過后端處理跨域,通過前端+服務器nginx處理。

1.前端涉及處理跨域的必要配置(開發環境、生產環境):vite3、vue3、axios

2.服務器涉及處理跨域的配置(生產環境):nginx【主要用到其配置文件nginx.conf】

3.配置開發環境【跟目錄下分別創建:.env.development、.env.production】

????????.env.development內容如下:

VITE_APP_PROXY_BASE_API='/proxyCustomerApi-dev'

????????.env.production內容如下:

VITE_APP_PROXY_BASE_API='/proxyCustomerApi-pro'

? ? ?tips: .env.development、.env.production中的常量命名須以"VITE_"開頭,這里定義的常量為VITE_APP_PROXY_BASE_API,值分別為"/proxyCustomerApi-dev"、"/proxyCustomerApi-pro"用以區分開發環境和生產環境,值可自定義為"/+自己想定義的內容"

4.前端vite.config.js中添加如下代碼(代碼中有相關注釋):

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import * as path from 'path';
... ...export default defineConfig((env) => {// 獲取到當前開發模式(dev/pro)下對應的環境文件對象值const evnMap = loadEnv(env.mode, process.cwd());// console.log(`evnMap = ${JSON.stringify(evnMap)}`);return {... ...server: {host: '0.0.0.0', // ip地址port: 8088, // 啟動端口// 反向代理配置,注意rewrite寫法,開始沒看文檔在這里踩了坑proxy: {// 本地開發環境通過代理實現跨域,生產環境使用 nginx 轉發// 對應項目根目錄 - [.env.development、.env.production]文件中的值[evnMap.VITE_APP_PROXY_BASE_API]: {target: 'http://xxx.xx.xx.xx:27005', // 請求報跨域錯誤的接口域名地址,真實請求地址changeOrigin: true, // 支持跨域rewrite: (path) =>path.replace(new RegExp('^' + evnMap.VITE_APP_PROXY_BASE_API), ''), // 重寫真實路徑,替換/apibypass: (req, res, options) => {const proxyUrl = options.target + options.rewrite(req.url);console.log(`真實請求的完整地址proxyUrl: ${proxyUrl}`);},},},},};
});

5.在自己封裝好的axios js文件中修改下axios.create中的配置,代碼如下:

const http = axios.create({// baseURL: DOMAIN,// import.meta.env.VITE_APP_PROXY_BASE_API 對應項目根目錄 - [.env.development、.env.production]文件中的值baseURL: import.meta.env.VITE_APP_PROXY_BASE_API,timeout: 600000,... ...
});export default http;

6.在自己出現跨域報錯的接口處修改成類似如下代碼片段:

export const chatHistoryRecordApi = {// 獲取所有客服與用戶對話列表getAllCustomerChatListPage: (params) => {return http({// import.meta.env.VITE_APP_PROXY_BASE_API 對應項目根目錄 - [.env.development、.env.production]文件中的值baseURL: import.meta.env.VITE_APP_PROXY_BASE_API,url: `/customer/allChatList`,method: 'get',params,});},// 查詢指定對話的聊天歷史記錄queryCurrentChatHistory: (params) => {return http({// import.meta.env.VITE_APP_PROXY_BASE_API 對應項目根目錄 - [.env.development、.env.production]文件中的值baseURL: import.meta.env.VITE_APP_PROXY_BASE_API,url: `/customer/chatHistory`,method: 'get',params,});},
};

至此前端跨域配置部分處理完成,可以調試開發環境【本地調試】了。

確保根目錄下的package.json文件中存在scripts標簽配置:

{"name": "hrosass","private": true,"version": "0.0.0","type": "module","scripts": {// dev、build系統會默認添加--mode production/development環境配置// "dev": "vite" =》"dev": "vite --mode development"// "build": "vite build" =》"build": "vite build --mode production""dev": "vite","build": "vite build",... ...},"dependencies": {... ...},"devDependencies": {... ...},"main": "index.js",... ...
}

本地調試命令行中執行(我項目是用的yarn來運行):yarn run dev,發現接口可以請求拿到數據了。但在線上生產環境下還是會報錯,如果只需要本地調試那到這里就完成了!!!

接下來處理生產環境(線上模式)下的跨域報錯問題,由于剛剛前端的配置中已經加上了對生產環境的代理配置,其實也就是根目錄下的這個文件【.env.production】。

7.本地連接上服務器,且服務器已配置好Nginx,找到Nginx的運行配置文件【nginx.conf】,內容大致如下(注意看注釋):

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;events {worker_connections 1024;
}http {log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log  /var/log/nginx/access.log  main;sendfile            on;tcp_nopush          on;tcp_nodelay         on;keepalive_timeout   65;types_hash_max_size 4096;client_max_body_size 20M;include             /etc/nginx/mime.types;default_type        application/octet-stream;# Load modular configuration files from the /etc/nginx/conf.d directory.# See http://nginx.org/en/docs/ngx_core_module.html#include# for more information.include /etc/nginx/conf.d/*.conf;map $http_upgrade $connection_upgrade {default upgrade;'' close;}# 加載vue前端項目的serverserver {listen       3004; # 端口server_name  localhost; # 域名location / {root  /home/view/wallet/dist/; # 打包vue項目后的dist存放路徑index  index.html index.htm; # 加載入口html文件try_files  $uri  $uri/  /index.html;}error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers PROFILE=SYSTEM;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }}

8.往server {?location / { } }下邊添加如下location反向代理配置(注意看注釋):

# /proxyCustomerApi-pro為前端 .env.production中的指定的值
location /proxyCustomerApi-pro {# 解決跨域add_header 'Access-Control-Allow-Origin' '*' always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;add_header 'Access-Control-Allow-Headers' 'Authorization,Refreshtoken,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;# 設置 options 請求處理if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*' always;add_header 'Access-Control-Max-Age' 1728000 always;add_header 'Content-Type' 'text/plain; charset=utf-8' always;add_header 'Content-Length' 0 always;# 對于Options方式的請求返回200或其它碼,表示接受跨域請求return 200;}# 設置反向代理 http://://xxx.xx.xx.xx:27005不加/會拼上/proxyCustomerApi-pro 加/不會拼/proxyCustomerApi-pro 由于真實接口請求中沒有/proxyCustomerApi-pro這段 這里不需要拼上 代理服務地址后應添加/   http://xxx.xx.xx.xx:27005/proxy_pass http://://xxx.xx.xx.xx:27005/; # 后端API地址 引起跨域報錯的api請求地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-NginX-Proxy true;proxy_http_version 1.1;proxy_connect_timeout 600;proxy_read_timeout 600;proxy_send_timeout 600;proxy_buffer_size 64k;proxy_buffers 4 64k;proxy_busy_buffers_size 128k;proxy_temp_file_write_size 128k;# 緩存時間,單位秒。這里設置的是6小時expires 21600s;# 收到304響應后,再次請求的時間間隔proxy_cache_valid 200 304 12h;}

9.配置后的nginx.conf完整內容如下:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;events {worker_connections 1024;
}http {log_format  main  '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log  /var/log/nginx/access.log  main;sendfile            on;tcp_nopush          on;tcp_nodelay         on;keepalive_timeout   65;types_hash_max_size 4096;client_max_body_size 20M;include             /etc/nginx/mime.types;default_type        application/octet-stream;# Load modular configuration files from the /etc/nginx/conf.d directory.# See http://nginx.org/en/docs/ngx_core_module.html#include# for more information.include /etc/nginx/conf.d/*.conf;map $http_upgrade $connection_upgrade {default upgrade;'' close;}# 加載vue前端項目的serverserver {listen       3004; # 端口server_name  localhost; # 域名location / {root  /home/view/wallet/dist/; # 打包vue項目后的dist存放路徑index  index.html index.htm; # 加載入口html文件try_files  $uri  $uri/  /index.html;}# /proxyCustomerApi-pro為前端 .env.production中的指定的值location /proxyCustomerApi-pro {# 解決跨域add_header 'Access-Control-Allow-Origin' '*' always;add_header 'Access-Control-Allow-Credentials' 'true' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;add_header 'Access-Control-Allow-Headers' 'Authorization,Refreshtoken,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type' always;# 設置 options 請求處理if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*' always;add_header 'Access-Control-Max-Age' 1728000 always;add_header 'Content-Type' 'text/plain; charset=utf-8' always;add_header 'Content-Length' 0 always;# 對于Options方式的請求返回200或其它碼,表示接受跨域請求return 200;}# 設置反向代理 http://://xxx.xx.xx.xx:27005不加/會拼上/proxyCustomerApi-pro 加/不會拼/proxyCustomerApi-pro 由于真實接口請求中沒有/proxyCustomerApi-pro這段 這里不需要拼上 代理服務地址后應添加/   http://xxx.xx.xx.xx:27005/proxy_pass http://://xxx.xx.xx.xx:27005/; # 后端API地址 引起跨域報錯的api請求地址proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header Host $http_host;proxy_set_header X-NginX-Proxy true;proxy_http_version 1.1;proxy_connect_timeout 600;proxy_read_timeout 600;proxy_send_timeout 600;proxy_buffer_size 64k;proxy_buffers 4 64k;proxy_busy_buffers_size 128k;proxy_temp_file_write_size 128k;# 緩存時間,單位秒。這里設置的是6小時expires 21600s;# 收到304響應后,再次請求的時間間隔proxy_cache_valid 200 304 12h;}error_page   500 502 503 504  /50x.html;location = /50x.html {root   html;}}# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2;
#        listen       [::]:443 ssl http2;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers PROFILE=SYSTEM;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }}

10.執行nginx命令【sudo service nginx reload】使配置生效,至此線上生產環境跨域配置完成。

調試線上跨域問題是否解決,前端項目執行:yarn run build打包線上版本生成dist文件夾并上傳到服務器,刷新線上網址發現接口可以請求拿到數據了。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/213375.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/213375.shtml
英文地址,請注明出處:http://en.pswp.cn/news/213375.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

銀行插件導致的Outlook客戶端無法連接服務器問題

問題現象 最近遇到好些同事出現outlook客戶端無法連接服務器的情況,具體現象就是右下角一直顯示【正在嘗試連接…】或者【需要密碼】,點擊【需要密碼】按鈕,輸密碼的彈窗是一個完全空白的頁面。 此時打開word,右上角那里去登錄o…

LeetCode19. Remove Nth Node From End of List

文章目錄 一、題目二、題解 一、題目 Given the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: Input: head [1,2,3,4,5], n 2 Output: [1,2,3,5] Example 2: Input: head [1], n 1 Output: [] Example 3: I…

智能優化算法應用:基于緞藍園丁鳥算法3D無線傳感器網絡(WSN)覆蓋優化 - 附代碼

智能優化算法應用:基于緞藍園丁鳥算法3D無線傳感器網絡(WSN)覆蓋優化 - 附代碼 文章目錄 智能優化算法應用:基于緞藍園丁鳥算法3D無線傳感器網絡(WSN)覆蓋優化 - 附代碼1.無線傳感網絡節點模型2.覆蓋數學模型及分析3.緞藍園丁鳥算法4.實驗參數設定5.算法…

自動數據增廣論文筆記 | AutoAugment: Learning Augmentation Strategies from Data

谷歌大腦出品 paper: https://arxiv.org/abs/1805.09501 這里是個論文的閱讀心得,筆記,不等同論文全部內容 文章目錄 一、摘要1.1 翻譯1.2 筆記 二、(第三部分)自動增強:直接在感興趣的數據集上搜索最佳增強策略2.1 翻譯2.2 筆記 三、(第四部分)實驗與結…

為什么說數字化轉型能幫助企業降本增效?

引言 數字化轉型是當今商業領域中的關鍵議題,它不僅是技術的應用,更是一種戰略性的變革,對企業而言具有重要意義。在這個數字化時代,企業需要不斷適應和采納新技術,以獲得競爭優勢并提高效率。 數字化轉型旨在將傳統業…

匿名內部類 - ( 零基礎學java )

Java-匿名內部類 我們先分析匿名內部類的結構,然后逐一解釋,最后以下羅列的問題都會在下面的內容中一一得到解答 : 匿名內部類到底是什么? 我們為什么要學習匿名內部類 ? 匿名內部類都有怎樣的作用 ? 匿名內部類應用的場景又有哪些 ? 匿名內部類是否有缺陷? 讓我們…

Java (JDK 21) 調用 OpenCV (4.8.0)

Java 調用 OpenCV 一.OpenCV 下載和安裝二.創建 Java Maven 項目三.其他測試 一.OpenCV 下載和安裝 Open CV 官網 可以下載編譯好的包,也可以下載源碼自行編譯 雙擊安裝 opencv-4.8.0-windows.exe 默認為當前目錄 安裝即解壓縮 根據系統位數選擇 將 x64 目錄下 op…

外匯交易到哪開戶?外匯開戶所需流程有哪些?

外匯交易是一種全球性的金融市場活動,參與者可以通過買入或賣出不同國家的貨幣來獲取利潤。在進行外匯交易之前,開設一個外匯交易賬戶是必要的。本文將介紹外匯交易開戶的重要性、選擇外匯交易平臺的因素以及開戶所需的基本流程,幫助讀者更好…

開往渤海的列車:滄港鐵路如何扮演產業帶城市生態共贏的關鍵先生

新時代構建新格局,新格局呼喚新作為。在交通強國戰略背景下,鐵路運輸企業需要如何彰顯“鐵擔當”? 逢山開路、遇水架橋,身處重要地理區位,滄州滄港鐵路有限公司(以下簡稱“滄港鐵路”)不斷搶抓…

并查集帶壓縮路徑的find

目錄 原因: 優化: 原因: 當路徑比較特殊,如圖: 非常深,最底層進行find時,循環找根(或者遞歸找),消耗就比較大。 我們可以進行優化。 優化: &…

【C++】C++異常語法、使用、規范、異常安全及異常的優缺點

1. C異常概念 異常是一種處理錯誤的方式,當一個函數發現自己無法處理的錯誤時就可以拋出異常,讓函數的直接或間接的調用者處理這個錯誤。 throw: 當問題出現時,程序會拋出一個異常。這是通過使用 throw 關鍵字來完成的。catch: 在您想要處理…

給你的Python程序添點Emoji魔法:使用Emoji模塊增添趣味和個性!

當你想給你的Python程序增添一些趣味和個性時,Emoji模塊是一個很有用的工具。Emoji模塊允許你在Python中使用各種表情符號,從笑臉到動物,甚至是食物和天氣等。在本篇博客中,我們將介紹如何在Python中使用Emoji模塊,并展…

【小白專用】使用PHP創建和操作MySQL數據庫,數據表

php數據庫操作 php連接mysql數據庫 <?php $hostlocalhost; // 數據庫主機名 $username"root"; // 數據庫用戶名 $password"al6"; // 數據庫密碼 $dbname"mysql"; // 數據庫名 $connIDmysqli_connect($host,$username,$password,$dbn…

adb push報錯:remote couldn‘t create file: Is a directory

adb push報錯&#xff1a;remote couldn‘t create file: Is a directory 出現這個問題可能是電腦本地目錄中包含中文或者是目錄地址中多包含了一個/ 比如說以下兩種路徑 1. test/測試音頻文件1/a.mp3 2.test/test_audio/ 這兩種都是不可以的&#xff08;我是在as中執行的…

MQTT服務質量-QoS

QoS是消息發送方和接收方之間的協議&#xff0c;定義了指定消息發送保證等級。本文將深入探究MQTT中不同的QoS等級。 QoS是什么 MQTT提供三個QoS等級&#xff1a; 最多一次&#xff08;QoS 0&#xff09;至少一次&#xff08;QoS 1&#xff09;確切一次&#xff08;QoS 2&am…

科技提升安全,基于YOLOv5系列模型【n/s/m/l/x】開發構建商超扶梯場景下行人安全行為姿態檢測識別系統

在商超等人流量較為密集的場景下經常會報道出現一些行人在扶梯上摔倒、受傷等問題&#xff0c;隨著AI技術的快速發展與不斷普及&#xff0c;越來越多的商超、地鐵等場景開始加裝專用的安全檢測預警系統&#xff0c;核心工作原理即使AI模型與攝像頭圖像視頻流的實時計算&#xf…

2024年JAVA招聘行情如何?

大家都在說Java求職不好找&#xff0c;是真的嗎&#xff1f;我們來看看數據。 數據支持&#xff1a;根據TIOBE 5月份的編程語言排行榜&#xff0c;Java仍然是前三名之一。這意味著&#xff0c;Java在開發領域仍然占據重要地位。 而在中國的IT市場中&#xff0c;Java仍然是主要…

使用alpine鏡像部署go應用時踩的坑

使用alpine鏡像部署go應用時踩的坑 關于交叉編譯 實際上我在ubuntu的交叉編譯出來的exe并不能在alpine上運行&#xff0c;這邊采取拉鏡像編譯復制出來的做法&#xff0c;部署再用干凈的alpine 拉取golang:alpine踩坑 在Dockerhub上可以找到&#xff1a; 然而拉取的alpine中…

在普通的項目中創建web的功能

新增web功能: 1.創建一個新項目&#xff0c;不勾選模板&#xff1a;2.添加web功能&#xff1a; 1.創建一個新項目&#xff0c;不勾選模板&#xff1a; 發現普通項目沒有webapp文件夾&#xff0c;即沒有web的功能。 2.添加web功能&#xff1a; Add framework support:添加一些…

VHDL數碼管顯示控制器設計

題目要求&#xff1a; 初始狀態&#xff0c;開關 K1 為低電平&#xff0c;6 個數碼管上依次顯示 1-6。當 K1 變為高電平時&#xff0c;數據管顯示內容依次循環左移&#xff0c;當 K1 變為低電平時&#xff0c;保持當前顯示內容。 參考資料&#xff1a;使用VHDL實現動態掃描八位…