vue axios 的详细用法

vue axios 的详细用法

axios是vue2.0以后推出的一个基于 promise 的 HTTP 库,说的直白一点就是用来发送http请求的。接下来我们来详细了解一下axios的使用方法。

1.比较原始的写法
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
}).then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
}).catch(function(err){
    console.log(err.response, '异常')
});
2.我们还可以像jq那样简写请求
axios.post('/user', {
		firstName: 'Fred',
		lastName: 'Flintstone'
	})
	.then(function(response) {
		console.log(response);
	})
	.catch(function(error) {
		console.log(error);
	});
axios.get('/user?ID=12345')
	.then(function(response) {
		// handle success
		console.log(response);
	})
	.catch(function(error) {
		// handle error
		console.log(error);
	})

在这里尤其要注意的是参数的传递,这是和jq很大的不同,axios的get请求的传参还有一种形式可以放在url后面,但是要注意写法

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })

post的请求传参尤其要注意,这里面有很大的坑
------如果你是像(下图)这样拼接参数,传到后台的参数形式变了,后台得不到参数,这个是axios的天生的缺陷
在这里插入图片描述
针对这种情况,我们有两种解决办法,一种是将参数换成键值对的形式axios.post(’/api/seller’, “userId=123456”),还有一种是采用vue官方的transformRequest方法。
在这里插入图片描述

发布了18 篇原创文章 · 获赞 3 · 访问量 1297

猜你喜欢

转载自blog.csdn.net/qq_22899129/article/details/100058553