代理跨域问题在前端开发中是经常遇到的,比较常用的是 jsonp,反向代理,CORS。今天我们看一下在vue3.x中如何配置代理跨域。
首先看下我们请求的服务器
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/word', function (req, res, next) {
// 打印get请求中的接口参数
res.json({
greeting:"hello word"
})
});
module.exports = router;
服务器为Express架构,这是路由,也就是我们请求会再这里做出相应
除此之外我们还需要配置app.js文件,这里允许有两种方式配置
第一种:app.all()
app.use(express.static(path.join(__dirname, 'public')));
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
app.use('/', index);
app.use('/users', users);
注:必须配置到加载路由之前、必须配置到加载路由之前、必须配置到加载路由之前
第二种:cors包
安装
npm install cors --save
代码配置在app.js
const cors = require('cors');
app.use(cors({
origin:['http://localhost:8080'],
methods:['GET','POST'],
}));
配置完服务端之后,我们需要在vue3.x下的vue.config.js中配置代理服务器
devServer: {
open: process.platform === 'darwin',
host: 'localhost',
port: 8080,
https: false,
hotOnly: false,
// 配置多个代理
proxy: {
"/api": {
target: "http://localhost:3000", // 要访问的接口域名
ws: true, // 是否启用websockets
changeOrigin: true, //开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
pathRewrite: {
"^/api": "" //这里理解成用'/api'代替target里面的地址,比如我要调用'http://40.00.100.100:3002/user/add',直接写'/api/user/add'即可
}
}
},
before: app => {
}
},
使用代理访问跨域服务端
我们这里使用axios进行get调用
使用之前我们配置全局axios,在Vue项目中找到main.js配置axios
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import plugin from '@/plugin/core'
import axios from 'axios'
//核心插件
Vue.use(plugin)
Vue.config.productionTip = false
Vue.prototype.axios = axios;
axios.defaults.timeout = 5000;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = '/api';
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
在我们需要使用的地方直接进行调用
methods:{
Click_axios:function(){
this.axios.get('/word').then(res => {
console.log("1");
}).catch(err => {
console.log("0")
})
}
}
结果