Created
August 31, 2020 08:28
-
-
Save gmailzj/93b70dc94628f1cb8738e39a161a8058 to your computer and use it in GitHub Desktop.
传递参数json和querystring
This file contains hidden or 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
| 前端向后端传输数据时,如果是get传输,直接传在url后;如果是post传输,则在请求体body中传输。 | |
| 在body中的数据格式又有两种,一种是 json 数据格式,另一种是 字符串。具体要用哪种格式取决于后端入参的格式。 | |
| 如果后端接收json数据类型,post 的 headers 需要设置 { ‘content-type’: ’application/json’ },传给后端的数据就形如 { ‘name’:’edward’, ‘age’:’25’ } | |
| 如果后端接收的是(表单)字符串类型,post 的 headers 需设置 { ‘content-type’: ’application/x-www-form-urlencoded’ }, | |
| ,传输给后端的数据就形如 ‘name=edward&age=25’ | |
| qs | |
| qs.stringfy() 将对象序列化成URL的形式 | |
| axios默认数据格式为json,所以: | |
| 1.当后端需要接收json格式的数据时,post请求头不需要设置请求头,数据格式也不需要我们去转换(若数据已经是json); | |
| 2.当后端需要接收字符串格式的数据时,我们需要给post请求头设置{ ‘content-type’: ’application/x-www-form-urlencoded’ }, | |
| 这个时候如果我们传的入参是一个 js 对象,这时候我们就需要用 qs 转换数据格式,qs具体用法如下: | |
| 安装模块:npm i qs -S | |
| 复制代码 | |
| import qs from 'qs'; | |
| const data = { name:'edward' , age:'25'}; // 我们传的是 js 对象 | |
| const options = { | |
| method: 'POST', | |
| headers: { 'content-type': 'application/x-www-form-urlencoded' }, | |
| data: qs.stringify(data), // 用 qs 将js对象转换为字符串 'name=edward&age=25' | |
| url: 'http://www.edward.com' | |
| }; | |
| axios(options); | |
| 复制代码 | |
| 我们也可以在封装axios的时候,给它全局设置qs | |
| axios.defaults.baseURL = 'https://api.example.com'; | |
| axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; | |
| axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; | |
| 【区分】: JSON.stringfy() 和 qs.stringfy() | |
| let data = { name: 'edward', age: '25' } | |
| 前者:JSON.stringfy(data) // ”{ 'name' : 'edward' , 'age' : '25' }” | |
| 后者:qs.stringfy(data) // 'name=edward&age=25' | |
| 【区分】:jQuery 中 $.ajax 的post请求 VS axios的post 请求的 content-type 默认值 | |
| 前者:"application/x-www-form-urlencoded" | |
| 后者:"application/json" | |
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| $.ajax({ | |
| type: 'POST', | |
| contentType: 'application/json;charset=utf-8', // 发送的数据类型 | |
| dataType: 'json', // 接收的数据类型 | |
| url: 'http://www.edward.com', | |
| data: JSON.stringfy(formData), | |
| success: function (res) { | |
| console.log(res.data) | |
| } | |
| }) | |
| contentType: 告诉服务器,我要发什么类型的数据 | |
| dataType:告诉服务器,我要想什么类型的数据,如果没有指定,那么会自动推断是返回 XML,还是JSON,还是script,还是String。 | |
| 注意 :$.ajax() post发送到服务器的数据。将自动转换为请求字符串格式。 | |
| 如果为对象,如 { name: 'edward', age: '25' },jQuery 将自动转化为 'name=edward&age=25' | |
| 如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment