前提: npm vue均已安装
1. 使用vue-cli搭建项目
cnpm install -g vue-cli
vue init webpack
image.png
2. 安装axios
npm install --save axios vue-axios
页面导入: import axios from 'axios'
创建api.js
import axios from 'axios'
import vue from 'vue'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 请求拦截器
axios.interceptors.request.use(function(config) {
return config;
}, function(error) {
return Promise.reject(error);
})
// 响应拦截器
axios.interceptors.response.use(function(response) {
return response;
}, function(error) {
return Promise.reject(error);
})
// 封装axios的get请求
export function GET(url, params) {
return new Promise((resolve, reject) => {
axios.get(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}
// 封装axios的post请求
export function POST(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}
// 封装axios的put请求
export function PUT(url, params) {
return new Promise((resolve, reject) => {
axios.put(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}
// 封装axios的delete请求
export function DELETE(url, params) {
return new Promise((resolve, reject) => {
axios.delete(url, params)
.then(response => {
resolve(response.data);
})
.catch((error) => {
reject(error);
})
})
}
export default {
GET_list(url, params) {
return GET(url, params);
}
}
安装json-server
npm install json-server -g
json-server db.json --port 8080
axios配置
proxyTable: {
'/api/': {
target: 'http://localhost:3003', //将http://localhost:3003映射到/api
changeOrigin: true, //是否跨域
pathRewrite: {
'^/api': '', // 因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/'
}
}
},
<script>
import api from './../axios/api.js'
import NewsCell from './NewsCell.vue'
export default {
name: 'index',
data () {
return {
newsListShow: [],
}
},
components: {
NewsCell
},
created() {
this.setNewsApi();
},
methods:{
setNewsApi: function() {
api.JH_news('/news/index', 'type=top&key=123456')
.then(res => {
console.log(res);
this.newsListShow = res.articles;
});
},
}
}
</script>
网友评论