1、解决跨域问题
如果 Vue 前端应用请求后端 API 服务器,出现跨域问题(CORS),如下图:
解决方法:在 Vue 项目中,打开 vue.config.js 配置文件,在配置文件中使用代理解决跨域问题。
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer:{
proxy: 'http://localhost:8085', //使用代理,解决跨域问题
}
})
注意:配置代理完成后,请求的URL前面不需要再加上完整的域名了,示例如下:
function getUserInfo(userId) {
//使用 axios 的 GET 请求
axios({
method: 'GET',
//注意:因为配置了代理服务器(解决跨域问题),所以请求的URL前面不需要再加上完整的域名
//url: `http://localhost:8085/user/getUserInfo/${userId}` //错误
url: `/user/getUserInfo/${userId}` //正确
}).then(
function (response) {
userInfo.value = response.data;
}
).catch