Vue 的axios的使用

时间:2022-07-25
本文章向大家介绍Vue 的axios的使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Vue 的axios的使用

首先,在vue项目中安装axios

npm install axios --save

全局引入时用

import axios from 'axios'
Vue.use(VueAxios,axios);

axios的get请求

getdata(){
  this.axios.get('xxxxx(url)')
  .then((response)=>{
       console.log(response.data)
   })
   .catch((response)=>{
       console.log(response)
   })
}

axios直接进行访问会出现跨域问题,需要配置代理了。(前提是服务器没有设置禁止跨域的权限问题)

config文件夹下的index.js文件中配置 (如果没有该文件就直接配置生成该文件放到项目最外层生成vue.config.js)

module.exports = {
    // devServer 配置本地服务器 
    devServer: {
		open:true,//自动打开浏览器
		// port: 8080,//自定义端口
		// 代理地址
		proxy: {
			'/api-search': {
				target:"https://m.kongfz.com", // 真正需要请求的地址
				changeOrigin: true, // 是否跨域(修改请求源)
			},
		}
	},
	
}
// https://m.kongfz.com/api-search/product/home/mobile?bizType=wap&host=msearch

配置好进行get请求

getData() {
	axios({
	method:"get",
	url:"/api-search/product/home/mobile?bizType=wap&host=msearch",
	headers: {"Content-Type": "application/json; charset=utf-8"}
		})
		.then(res => {
			console.log('数据是:', res);
		})
		.catch(err => {
			console.log('获取数据失败', err);
		});	
}

这样get请求就会跨域获取到数据了

记得配置修改完项目要重启