国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

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

這篇具有很好參考價值的文章主要介紹了記:vite3+vue3+axios前端項目跨域問題解決【前端和服務(wù)器nginx配置】。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

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

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

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

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

3.配置開發(fā)環(huán)境【跟目錄下分別創(chuàng)建:.env.development、.env.production】

????????.env.development內(nèi)容如下:

VITE_APP_PROXY_BASE_API='/proxyCustomerApi-dev'

????????.env.production內(nèi)容如下:

VITE_APP_PROXY_BASE_API='/proxyCustomerApi-pro'

? ? ?tips: .env.development、.env.production中的常量命名須以"VITE_"開頭,這里定義的常量為VITE_APP_PROXY_BASE_API,值分別為"/proxyCustomerApi-dev"、"/proxyCustomerApi-pro"用以區(qū)分開發(fā)環(huán)境和生產(chǎn)環(huán)境,值可自定義為"/+自己想定義的內(nèi)容"

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

import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import * as path from 'path';
... ...

export default defineConfig((env) => {
    // 獲取到當(dāng)前開發(fā)模式(dev/pro)下對應(yīng)的環(huán)境文件對象值
	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: {
				// 本地開發(fā)環(huán)境通過代理實現(xiàn)跨域,生產(chǎn)環(huán)境使用 nginx 轉(zhuǎn)發(fā)
				// 對應(yīng)項目根目錄 - [.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), ''), // 重寫真實路徑,替換/api
					bypass: (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 對應(yīng)項目根目錄 - [.env.development、.env.production]文件中的值
	baseURL: import.meta.env.VITE_APP_PROXY_BASE_API,
	timeout: 600000,
    ... ...
});

export default http;

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

export const chatHistoryRecordApi = {
	// 獲取所有客服與用戶對話列表
	getAllCustomerChatListPage: (params) => {
		return http({
			// import.meta.env.VITE_APP_PROXY_BASE_API 對應(yīng)項目根目錄 - [.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 對應(yīng)項目根目錄 - [.env.development、.env.production]文件中的值
			baseURL: import.meta.env.VITE_APP_PROXY_BASE_API,
			url: `/customer/chatHistory`,
			method: 'get',
			params,
		});
	},
};

至此前端跨域配置部分處理完成,可以調(diào)試開發(fā)環(huán)境【本地調(diào)試】了。

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

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

本地調(diào)試命令行中執(zhí)行(我項目是用的yarn來運行):yarn run dev,發(fā)現(xiàn)接口可以請求拿到數(shù)據(jù)了。但在線上生產(chǎn)環(huán)境下還是會報錯,如果只需要本地調(diào)試那到這里就完成了?。?!

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

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

# 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前端項目的server
  server {
        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;
            # 設(shè)置 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;
            }
            # 設(shè)置反向代理 http://://xxx.xx.xx.xx:27005不加/會拼上/proxyCustomerApi-pro 加/不會拼/proxyCustomerApi-pro 由于真實接口請求中沒有/proxyCustomerApi-pro這段 這里不需要拼上 代理服務(wù)地址后應(yīng)添加/   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;
            # 緩存時間,單位秒。這里設(shè)置的是6小時
            expires 21600s;
            # 收到304響應(yīng)后,再次請求的時間間隔
            proxy_cache_valid 200 304 12h;
        }

9.配置后的nginx.conf完整內(nèi)容如下:

# 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前端項目的server
  server {
        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;
            # 設(shè)置 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;
            }
            # 設(shè)置反向代理 http://://xxx.xx.xx.xx:27005不加/會拼上/proxyCustomerApi-pro 加/不會拼/proxyCustomerApi-pro 由于真實接口請求中沒有/proxyCustomerApi-pro這段 這里不需要拼上 代理服務(wù)地址后應(yīng)添加/   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;
            # 緩存時間,單位秒。這里設(shè)置的是6小時
            expires 21600s;
            # 收到304響應(yīng)后,再次請求的時間間隔
            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.執(zhí)行nginx命令【sudo service nginx reload】使配置生效,至此線上生產(chǎn)環(huán)境跨域配置完成。

調(diào)試線上跨域問題是否解決,前端項目執(zhí)行:yarn run build打包線上版本生成dist文件夾并上傳到服務(wù)器,刷新線上網(wǎng)址發(fā)現(xiàn)接口可以請求拿到數(shù)據(jù)了。文章來源地址http://www.zghlxwxcb.cn/news/detail-791298.html

到了這里,關(guān)于記:vite3+vue3+axios前端項目跨域問題解決【前端和服務(wù)器nginx配置】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • vue3項目創(chuàng)建(vite3+ts+elementui-plus)

    vue3項目創(chuàng)建(vite3+ts+elementui-plus)

    目的:vue3+vite+ts 安裝依賴,安裝vite的工具 Vite下一代的前端工具鏈為開發(fā)提供極速響應(yīng)v4.3 創(chuàng)建工程 –template vue-ts 后面的是配置模板,有很多,也有react,官網(wǎng)有介紹 啟動工程 安裝路由 配置vite-env.d.ts 為了讓ts識別.vue文件 安裝element-plus 注意vue3用的是element-plus別裝錯版本了

    2024年02月16日
    瀏覽(19)
  • 【Vue.js】Vue3全局配置Axios并解決跨域請求問題

    【Vue.js】Vue3全局配置Axios并解決跨域請求問題

    對于前后端分離項目,前端和后端端口不能重復(fù),否則會導(dǎo)致前端或者后端服務(wù)起不來。例如前端訪問地址為: http://localhost:8080/ ,后端訪問地址為 http://localhost:8081/ 。后端寫好Controller,當(dāng)用Axios訪問該接口時,將會報錯: Access to XMLHttpRequest at \\\' http://localhost:8081/login \\\' from

    2024年02月05日
    瀏覽(29)
  • Soybean Admin - 基于 Vue3 / vite3 等最新前端技術(shù)棧構(gòu)建的中后臺模板,免費開源、清新優(yōu)雅,主題豐富

    Soybean Admin - 基于 Vue3 / vite3 等最新前端技術(shù)棧構(gòu)建的中后臺模板,免費開源、清新優(yōu)雅,主題豐富

    一款專業(yè)好看、完成度很高的 admin 開源項目,無論是用于生產(chǎn)還是學(xué)習(xí),都非常值得嘗試。 關(guān)于 Soybean Admin Soybean Admin 是一個基于 Vue3 / Vite3 / TypeScript / NaiveUI / Pinia 和 UnoCSS 的中后臺模版,它使用了最新流行的前端技術(shù)棧,內(nèi)置豐富的主題配置,有著極高的代碼規(guī)范,基于文

    2024年02月11日
    瀏覽(21)
  • 解決Vue3+Vite3 打包部署到nginx后配置非根目錄刷新頁面報錯空白

    解決Vue3+Vite3 打包部署到nginx后配置非根目錄刷新頁面報錯空白

    報錯內(nèi)容 解決方法 router文件 vite.config.ts nginx.conf 配置中路徑apps是我自建的存放前端頁面的文件夾 起關(guān)鍵作用的是 try_files $uri $uri/ /demo/index.html ,當(dāng)然上面項目文件夾demo也需保持一致 alias 后面的路徑是Vue項目打包后dist靜態(tài)文件服務(wù)器存放路徑,一般在nginx下面建一個文件夾

    2024年02月11日
    瀏覽(99)
  • vue項目使用vite設(shè)置proxy代理,vite.config.js配置,解決本地跨域問題

    vue項目使用vite設(shè)置proxy代理,vite.config.js配置,解決本地跨域問題

    非同源請求,也就是協(xié)議(protocol)、端口(port)、主機(host)其中一項不相同的時候,這時候就會產(chǎn)生跨域 vite的proxy代理和vue-cli的proxy大致相同,需要在vite.config.js文件中配置(打包配置也在此) 代理配置在server中,可以上vite官網(wǎng)服務(wù)器選項查看server.proxy代碼示例:開發(fā)服務(wù)器選

    2024年01月21日
    瀏覽(30)
  • vue3+vite項目跨域配置(踩坑無數(shù)篇)

    寫這篇多少有點心情復(fù)雜,畢竟因為一個巨巨巨巨沒意思的bug卡了兩整天… 廢話不多說啦,開篇入題叭,希望大家都能改好自己的bugggggg?。?! 1.vite.config.js配置 注意:因為我是用 vite 創(chuàng)建的,不是vue-cli,當(dāng)時搜了好多教程都教的是新建一個vue.config.js,發(fā)現(xiàn)根本沒有生效,

    2024年02月05日
    瀏覽(26)
  • vue3 vite配置跨域以及不生效問題

    1. 在vite.config中添加配置 2. 在.env.development中配置開發(fā)環(huán)境下的基地址(沒有該文件夾手動新建) 3. 配置axios的基地址 最后: ? ? ? ? 我之前是犯過一個錯誤的, 導(dǎo)致我搞了半天都沒搞好... 就是配置完vite.config, 那個/ccc后綴是接口沒有的自己加的, 那么就要手動加上去了...? ? ?

    2024年02月11日
    瀏覽(81)
  • vue3初始搭建項目完整教程 vue3 + vite + element-ui + axios

    vue3初始搭建項目完整教程 vue3 + vite + element-ui + axios

    1. 安裝 2. 創(chuàng)建目錄 3. 在router下新增index.js 4.修改main.ts 1. 新增文件夾 2. 新增Home.vue和About.vue 1. 修改app.vue 1.unplugin-auto-import 2. 在vite.config.js中引入 1.安裝element-ui 2. 按需導(dǎo)入 3.在vite.config.js新增插件 4.測試是否引入成功 5.如果報錯 1. 網(wǎng)上下載reset.css 2.在assets中新增css文件夾 3.將

    2024年02月16日
    瀏覽(54)
  • 新建vite+vue3+ts項目,以及解決過程中遇到的問題

    新建vite+vue3+ts項目,以及解決過程中遇到的問題

    目錄 一、新建vite+vue3+ts項目 二、解決過程中遇到的問題 解決報錯:Module ‘“xx.vue“‘ has no default export. 解決報錯:Error [ERR_MODULE_NOT_FOUND]: Cannot find package ‘uuid’ imported from xxx的解決 解決報錯:[plugin:vite:css] Preprocessor dependency \\\"less\\\" not found. Did you install it? 此處我使用npm做一下

    2024年02月06日
    瀏覽(78)
  • vite3、vue 項目打包分包進階-組件分包

    vite3、vue 項目打包分包進階-組件分包

    在上次的分包實戰(zhàn)后,我在服務(wù)器上測試了分包后的項目效果很好,但是還不夠理想,因為在我的Login頁面我使用的動態(tài)組件,其中包含注冊組件register、忘記密碼組件renew,我們知道vite的打包機制是由各個分入口匯總到一個總文件,那么我們該怎么做呢? vite打包實戰(zhàn),在這篇

    2023年04月23日
    瀏覽(25)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包