axios

GET请求不一样方式结果不一样前端

官方文档咱们能够看到的示例demo以下:webpack


// 直接在请求理解里面拼接参数get参数
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});ios

// 或者是使用对象的方式填写params参数
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
上面的示例代码看起来是同样的,其实有个细节仍是不同的,就是使用第二种方式会对参数值执行encodeURIComponent。web

看个人一段代码:npm

// 直接在请求理解里面拼接参数get参数
axios.get('/user?testurl=http://test.aaa.com')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});axios

// 或者是使用对象的方式填写params参数
axios.get('/user', {
params: {
testurl: 'http://test.aaa.com'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

在浏览器端测试后观察请求的url的参数能够发现。后端

 

第一种方式,没有对参数进行编码。第二种方式能够看到对参数进行了encodeURIComponent操做。因此在使用的过程当中,若是咱们的后端须要前端在传递参数前对某些参数进行encodeURIComponent。在使用这两种方式的时候能够注意一下,防止多encode一次形成后端接受参数错误。浏览器

POST请求的发送app

我主要是在浏览器端使用axios来发送请求。并且它的请求返回的是一个Promise对象。我能够很方便的处理请求的结果。post

在官方文档中是这样描述的,若是在浏览器端须要发送post请求,须要使用URLSearchParams。

var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

可是在官方文档中也很明确的说明了URLSearchParams不是支持全部的浏览器的。咱们须要使用polyfill来兼容一些低版本的浏览器。

或者是使用qs来对url进行编码。


// npm install qs --save or yarn add qs

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));

这里说下使用polyfill会遇到的问题。官方推荐的polyfill是url-search-params。说明中是这样描述的:

Note that URLSearchParams is not supported by all browsers (see caniuse.com), but there is a polyfill available (make sure to polyfill the global environment)。
当咱们的使用webpack或者是fis3开发的 时候默认都是把npm依赖做为依赖包来处理的。这里的global其实就是让咱们不要把这个文件做为一个Npm依赖包,并且直接引入到咱们的Html中。

好比在咱们的body标签的底部

<body>

<script src="../xxxx/url-search-params.js"></script>
</body>


那么我若是我想使用CMD规范或者是ES6 的import呢?咱们可使用url-search-params-polyfill

参考文档后,若是咱们想要使用CMD规范:

require('url-search-params-polyfill');


ES6的写法

import 'url-search-params-polyfill';


也能够直接在Html标签中直接引用:

<script src="index.js"></script>

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息