1. What is the function of axios?
concept
Axios is essentially an encapsulation of native XMLHttpRequest, a promise-based HTTP library that can be used in browsers and node.js.
characteristic
- Create XMLHttpRequests from the browser
- Create http request from node.js
- Support Promise API
- Intercept requests and responses
- Transform request data and response data
- cancel request
- Automatically convert JSON data
- Client supports defense against XSRF
2. Download and reference of axios
npm install
npm install axios
main.js
Introduced in the file of the vue projectaxios
import axios from 'axios'
3. Use in componentsaxios
What are the several request methods commonly used by Axios:
- get: (generally used) to get data
- post: submit data (form submission + file upload)
- put: update (or edit) data (all data is pushed to the backend (or server))
- patch: update data (only push the modified data to the backend)
- delete: delete data
get request (without parameters)
export default {
name:'App',
methods:{
getStudents(){
axios.get('http://localhost:8080/atguigu/students').then(
response=>{
//response.data 返回拿回来的数据
console.log('请求成功了',response.data);
},
error=>{
//error.message 返回错误的原因
console.log('请求失败了',error.message);
}
)
}
}
get request (with parameters)
export default {
name:'Search',
data() {
return {
//携带的数据
keyWord:''
}
},
methods:{
searchUsers(){
//发送请求
axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
response=>{
console.log('请求成功了',response.data);
},
error=>{
console.log('请求失败了',error.message);
}
)
},
}
}
post request
axios.post('/url', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});