Created
July 1, 2019 09:24
-
-
Save lessfish/feba271e6f479c17762f43f7d949504a to your computer and use it in GitHub Desktop.
axios 搭建 http 请求例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import request from './request' | |
export const getData = (name, age) => { | |
return request({ | |
url: '/get', | |
params: { | |
name, | |
age | |
} | |
}) | |
} | |
export const postData = (name, age) => { | |
return request({ | |
method: 'post', | |
url: '/post', | |
data: { | |
name, | |
age | |
} | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { getData, postData } from './api' | |
getData('fish', 30).then(res => { | |
console.log(res) | |
}).catch(err => {}) | |
postData('fish', 30).then(res => { | |
console.log(res) | |
}).catch(err => {}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
// 这里通常应该根据环境判断 | |
const baseURL = 'https://httpbin.org' | |
const request = axios.create({ | |
baseURL, | |
timeout: 15000, | |
}) | |
// 请求拦截,可以在这里增加 headers 设置等 | |
request.interceptors.request.use(config => { | |
// config.headers['Access-Token'] = 'xxx' | |
return config | |
}, error => { | |
Promise.reject(error) | |
}) | |
// 返回拦截,可以在这里统一做错误处理 | |
request.interceptors.response.use( | |
response => { | |
// 只返回 data | |
// response <https://github.com/axios/axios#response-schema> | |
const res = response.data | |
return res | |
}, | |
error => { | |
return Promise.reject(error) | |
} | |
) | |
export default request |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment