axios在vue中的get和post使用

一、axios作用是什么?

概念

Axios 本质上还是对原生XMLHttpRequest的封装,一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

特性

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

二、axios的下载和引用

npm安装

npm install axios

在vue项目的main.js文件中引入axios

import axios from 'axios'

三、在组件中使用axios

Axios常用的几种请求方法有哪些:

  • get:(一般用于)获取数据
  • post:提交数据(表单提交+文件上传)
  • put:更新(或编辑)数据(所有数据推送到后端(或服务端))
  • patch:更新数据(只将修改的数据推送到后端)
  • delete:删除数据

get 请求(不带参数)

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 请求(带参数)

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 请求

axios.post('/url', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

猜你喜欢

转载自blog.csdn.net/m0_60263299/article/details/123922005
今日推荐