解决跨域的情况一般就是如下图:
Vue 中配置跨域的配置在 vue.config.js 文件中添加:
配置一个的写法
module.exports = {
devServer: {
proxy: 'http://localhost:5000'
}
}
配置多个的写法
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
pathRewrite: { '^/api': '' },
ws: true,
changeOrigin: true
},
'/api2': {
target: 'http://localhost:6000',
pathRewrite: { '^/api2': '' },
ws: true,
changeOrigin: true
}
}
}
}
添加完代理服务器的相关配置,就需要通过 ajax 请求访问服务器了,一般 vue 中使用的都是 axios 库,这里就以 axios 库为例子:
安装 axios
npm i axios
使用 axios
import axios from 'axios'
export default {
name: 'Student',
methods: {
注释内容 `:get 请求访问 /api 前缀开头的地址,实际上访问的地址是: http://localhost:5000/request_url`
test1() {
axios.get('http://localhost:8080/api/request_url').then(res => {
console.log(res.data);
});
},
注释内容 :`get 请求访问 /api2 前端开头的地址,实际上访问的地址是:http://localhost:6000/request_url`
test2() {
axios.get('http://localhost:8080/api2/request_url').then(res => {
console.log(res.data);
})
}
}
}