axios 发请求
全局引入axios:main.js
import axios from 'axios'
Vue.prototype.$axios = axios
在组件里使用:
this.$axios.get/post("路径")
axios二次封装
1.在src文件夹里创建一个api文件夹,里面创建一个request.js和index.js
//request.js文件夹里面写:
import axios from 'axios'
const service = axios.create({
//baseUrl:'http://m.maoyan.com',
timeout:1000,//以毫秒为单位
})
export default service;
2.然后在index.js里面,发送请求
import service from './request'
//这里有两种导出方式
//export导出多个对象,导出对象需要用{ }
export const getList = () => {
return service.get("/ajax/movieOnInfoList?token=", {
//如果有其他内容,就在这里面写,比如说params{a:5} 想当于?a=5
})
}
//导出只能导出一个对象,export default导出对象不需要{ }
export default = {
getList(){
return service.get("/ajax/movieOnInfoList?token=", {
//如果有其他内容,就在这里面写,比如说params{a:5} 想当于?a=5
})
}
}
3.需要在根目录下进行代理跨域创建一个 Vue.config.js文件
//这里如果拿不到数据,是因为存在跨域问题
//需要在根目录下进行代理跨域
module.exports = {
devServer:{
proxy:{
"/my":{
target:"http://m.maoyan.com", //目标地址
changeOrigin:true, //是否换源
pathRewrite:{
"^/my":"/" //path重写
}
}
}
}
}
4.在需要请求的组件中导入
//这里有两种写法:
//1. 如果在index.js导入单个方法,export导出。必须使用跟index.js里方法相同的方法名getList
import { getList } from "@/api"
//2.如果是export default导出,这里导入就不需要{}
//.then之后对数据进行操作
export default {
getList().then(res => {
console.log(res)
})
}
axios的选项和拦截项
选项对象 -- 设置公共url
在main.js或request.js中:
import axios from 'axios'
var url = "http://jsonplaceholder.typicode.com"
var service = axios.create({
baseUrl:url, //前缀
timeout:1000, //超时时间
headers:{'X-Custom-Header' : 'foobar'}, //请求头信息
params:{a:5} //相当于url?a=5
})
在需要请求的.vue文件中
created(){
this.$axios.get(url+"/posts").then((res) => {
console.log(res)
})
}
拦截器 -- interceptors
分类:request(请求拦截器)和response(响应拦截器)
拦截器的作用是相当于中间件的作用,因为有些数据埋藏比较深,分很多层,运用拦截器就能够将多层在拦截器中只写一次,请求返回的就是单层或者双层,使用的时候就方便了。
在request.js里面写response拦截器:
service.interceptors.response.use((res) => res.data)
正向代理和反向代理
正向代理
Vue.config.js 在项目的根目录下
module.exports={
devServer:{
proxy:{
"/my" :{
"target" : "url",
"changOrigin" : true,
"pathRewrite" : {
"^/my" :"/"
}
}
}
}
}
更改之后一定重启项目才生效