補充:問題:CORS ,前后端訪問跨域問題
我這邊的解決方法是:
myAxios.defaults.withCredentials = true; // 配置為true,表示前端向后端發送請求的時候,需要攜帶上憑證cookie
整體的:
import axios from "axios";// axios.defaults.withCredentials = true; // 允許攜帶憑證
// const isDev = process.env.NODE_ENV === 'development';// 創建實例時配置默認值
const myAxios = axios.create({LookupAddress: undefined, LookupAddressEntry: undefined,baseURL: 'http://localhost:8080/api'
});// const myAxios: AxiosInstance = axios.create({
// baseURL: isDev ? 'http://localhost:8080/api' : '線上地址',
// });myAxios.defaults.withCredentials = true; // 配置為true,表示前端向后端發送請求的時候,需要攜帶上憑證cookie
// 創建實例后修改默認值// 添加請求攔截器
myAxios.interceptors.request.use(function (config) {// 在發送請求之前做些什么console.log('我要發請求了')return config;
}, function (error) {// 對請求錯誤做些什么return Promise.reject(error);
});// 添加響應攔截器
myAxios.interceptors.response.use(function (response) {// 2xx 范圍內的狀態碼都會觸發該函數。// 對響應數據做點什么console.log('我收到你的響應了',response)return response.data;
}, function (error) {// 超出 2xx 范圍的狀態碼都會觸發該函數。// 對響應錯誤做點什么return Promise.reject(error);
});// Add a request interceptor
// myAxios.interceptors.request.use(function (config) {
// console.log('我要發請求啦', config)
// // Do something before request is sent
// return config;
// }, function (error) {
// // Do something with request error
// return Promise.reject(error);
// });
//
//
// // Add a response interceptor
// myAxios.interceptors.response.use(function (response) {
// console.log('我收到你的響應啦', response)
// // 未登錄則跳轉到登錄頁
// if (response?.data?.code === 40100) {
// const redirectUrl = window.location.href;
// window.location.href = `/user/login?redirect=${redirectUrl}`;
// }
// // Do something with response data
// return response.data;
// }, function (error) {
// // Do something with response error
// return Promise.reject(error);
// });export default myAxios;
后端配置:
在 Spring Boot 中,可以通過在配置類中添加 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">@CrossOrigin</font>
注解或實現 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">WebMvcConfigurer</font>
接口并重寫 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">addCorsMappings</font>
方法來允許特定來源的跨域請求:
package com.rainbowsea.yupao.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** 跨域配置**/
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {//設置允許跨域的路徑registry.addMapping("/**")//設置允許跨域請求的域名//當**Credentials為true時,**Origin不能為星號,需為具體的ip地址【如果接口不帶cookie,ip無需設成具體ip】.allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http" +"://127.0.0.1:8083","http://127.0.0.1:8080","http://127.0.0.1:5173")//是否允許證書 不再默認開啟.allowCredentials(true)//設置允許的方法.allowedMethods("*")//跨域允許時間.maxAge(3600);}
}
相關博客鏈接:
- https://blog.csdn.net/yuanlong12178/article/details/147143201 參考該 blog 解決的
- https://blog.csdn.net/xhmico/article/details/122338365 這篇也不錯。
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'// 導出配置對象,使用ES模塊語法
export default defineConfig({plugins: [vue()], // 啟用Vue插件server: { // 注意:在Vite的新版本中,配置項`devServer`已更名為`server`proxy: {'/api': {target: 'http://localhost:8080/api', // 目標服務器地址changeOrigin: true, // 是否改變源// 如果需要路徑重寫,可以取消以下行的注釋// pathRewrite: { 1'^/api': '' }}}}
});
https://blog.csdn.net/yuanlong12178/article/details/147143201 內容備份如下:
一、Vue.js 中跨域請求未配置 CORS 的常見原因
(一)瀏覽器的同源策略限制
瀏覽器的同源策略限制了從一個源加載的文檔或腳本與來自另一個源的資源之間的交互能力。當你的前端應用和后端 API 位于不同的域或端口時,就會觸發 CORS 問題。
(二)后端未正確配置 CORS
如果后端服務器未正確設置 CORS 相關的響應頭,瀏覽器將無法允許跨域請求。
二、解決方案
(一)后端配置 CORS
在后端服務器上進行 CORS 配置是解決跨域問題的根本方法。以下是一些常見后端框架的 CORS 配置示例:
- Node.js (使用 Express)
const express = require('express');
const cors = require('cors');
const app = express();app.use(cors({origin: 'http://localhost:8080', // 允許的源methods: ['GET', 'POST', 'PUT', 'DELETE'], // 允許的 HTTP 方法allowedHeaders: ['Content-Type', 'Authorization'] // 允許的頭部字段
}));app.get('/api/data', (req, res) => {res.json({ message: 'CORS is working!' });
});app.listen(3000, () => {console.log('Server is running on port 3000');
});
2. Spring Boot
在 Spring Boot 中,可以通過在配置類中添加 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">@CrossOrigin</font>
注解或實現 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">WebMvcConfigurer</font>
接口并重寫 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">addCorsMappings</font>
方法來允許特定來源的跨域請求:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/api/**").allowedOrigins("http://localhost:8080").allowedMethods("GET", "POST", "PUT", "DELETE").allowCredentials(true);}
}
(二)前端配置代理
在開發環境中,可以通過配置代理服務器來繞過瀏覽器的同源策略限制。Vue CLI 提供了代理配置功能,可以通過修改 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">vue.config.js</font>
文件中的 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">devServer.proxy</font>
選項來實現。
module.exports = {devServer: {proxy: {'/api': {target: 'http://api.example.com', // 目標服務器changeOrigin: true, // 是否改變源pathRewrite: { '^/api': '' } // 路徑重寫}}}
};
(三)使用第三方庫
使用像 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);">cors</font>
這樣的第三方庫可以大大簡化 CORS 的配置過程。安裝庫后,可以在后端應用中引入并配置它:
const cors = require('cors');
const express = require('express');const app = express();app.use(cors({origin: 'http://localhost:8080',methods: 'GET,POST,PUT,DELETE',allowedHeaders: 'Content-Type,Authorization'
}));// Rest of the server setup
(四)JSONP(不推薦)
JSONP 是一種較老的跨域解決方案,通過 <font style="color:rgb(199, 37, 78);background-color:rgb(249, 242, 244);"><script></font>
標簽的跨域加載機制來實現。它只支持 GET 請求,且存在安全風險,因此在現代應用中不推薦使用。
三、最佳實踐建議
(一)優先在后端配置 CORS
在生產環境中,優先在后端服務器上進行 CORS 配置,以確保安全性。
(二)開發環境使用代理
在開發環境中,使用 Vue CLI 的代理功能來解決跨域問題,避免修改后端代碼。
(三)避免使用 JSONP
由于 JSONP 存在安全風險且只支持 GET 請求,建議避免使用。
四、總結
在 Vue.js 中,解決跨域請求未配置 CORS 的問題可以通過后端配置 CORS、前端配置代理、使用第三方庫等方法來實現。后端配置 CORS 是最推薦的方法,因為它可以確保生產環境的安全性。在開發環境中,使用 Vue CLI 的代理功能可以快速解決跨域問題。希望本文的介紹能幫助你在 Vue.js 開發中更好地處理跨域請求,提升應用的性能和用戶體驗。
最后:
“在這個最后的篇章中,我要表達我對每一位讀者的感激之情。你們的關注和回復是我創作的動力源泉,我從你們身上吸取了無盡的靈感與勇氣。我會將你們的鼓勵留在心底,繼續在其他的領域奮斗。感謝你們,我們總會在某個時刻再次相遇。”