在要使用axios的文件中引入axiosvue
1.main.js文件 :import axios from 'axois' 2.要发送请求的文件:import axios from 'axois'
在config/index.js文件设置代理ios
dev: { proxyTable: {// 输入/api 让其去访问http://localhost:3000/api '/api':{ target:'http://localhost:3000'//设置调用的接口域名和端口号 ( 设置代理目标) }, '/api/*':{ target:'http://localhost:3000' }, changeOrigin: true, pathRewrite: { //路径重写 '^/api': '/' //这里理解成用‘/api’代替target里面的地址,后面组件中咱们掉接口时直接用api代替 好比我要调用'http://localhost:3002/user/add',直接写‘/api/goods/add’便可 } } 试一下,跨域成功,可是这知识开发环境(dev)中解决了跨域问题,生产环境中正真部署到服务器上若是是非同源仍是存在跨域问题。
// 向具备指定id的用户发出请求 axios.get('/user?id=1001') .then(function (response) { console.log(response.data); }).catch(function (error) { console.log(error); }); // 也能够经过 params 对象传递参数 axios.get('/user', { params: { id: 1001 } }).then(function (response) {//请求成功回调函数 console.log(response); }).catch(function (error) {//请求失败时的回调函数 console.log(error); });
axios.post('/user', { userId: '10001' //注意post请求发送参数的方式和get请求方式是有区别的 }).then(function (response) { console.log(response); }).catch(function (error) { console.log(error); });