🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
1.配置vue.config.js ``` module.exports = { devServer: { port: 8003 } } ``` npm run serve ``` 2.https://cnodejs.org/api/v1/topics ``` 3.下载包axios ``` npm i axios -S ``` 4.创建文件axios.vue ``` <template> <div>axios发送请求</div> </template> <script> import axios from 'axios' export default { created(){ axios.get('https://cnodejs.org/api/v1/topics')//params:{} .then((result)=>{ console.log(result) }) .catch((error)=>{ console.log(error) }) } } </script> <style> </style> ``` 5.在app.vue引入组件 reuslt.data.data. 6.如果没有数据返回可能是跨域 CORS 7.解决跨域问题 设置代理 vue.config.js ``` module.exports = { devServer: { port: 8003, proxy: { '/api': { target: 'https://cnodejs.org' //:8080 } } } } ``` ``` import axios from 'axios' export default { name : 'MyConent', data(){ return{ arr :[] } }, created(){ axios.get('/api/v1/topics')//params:{} .then((result)=>{ // console.log(result.data) this.arr = result.data.data; console.log(this.arr); }) .catch((error)=>{ console.log(error) }) } } ``` 8.封装axios请求 在src下新建文件夹request,新建文件api.js ``` import axios from 'axios' export const request = data => axios.get('/api/v1/topics') // const request = data => axios.get('/api/v1/topics',{params:data}) ``` ``` 把原来的改成 // import axios from 'axios' import {request} from '../request/api' export default { name : 'MyConent', data(){ return{ arr :[] } }, created(){ request()//params:{} .then((result)=>{ // console.log(result.data) this.arr = result.data.data; console.log(this.arr); }) .catch((error)=>{ console.log(error) }) } } ``` 9.封装拦截器 在文件夹request,新建文件request.js 目的 封装axios ``` import axios from 'axios' import { Promise } from 'core-js'; const instance = axios.create({ timeout: 10000 }) instance.interceptors.request.use(config => { console.log(config) //数据处理 (json,fromdata) return config; //验证token //config.params.token = 123 }, err => { return new Promise.reject(err); }) instance.interceptors.response.use(result => { console.log(result) return result; }, err => { return new Promise.reject(err); }) export default instance ``` 10.修改api.js文件 ``` // import axios from 'axios' import request from './request' export const getRest = () => request.get('/api/v1/topics') // const request = data => axios.get('/api/v1/topics',{params:data}) ```