前后端关于post请求中,对body的不同数据格式的解决处理方案实现

来源:互联网 发布:淘宝上的摩托车靠谱吗 编辑:程序博客网 时间:2024/05/22 09:00
针对在全端开发中发送请求的方式以及后端接收解析处理方式的汇总,基于js全栈的解决方案,如果是熟悉js的小伙伴福利来了!

本文分为前端请求,后端请求,后端处理三部分来详细解读 【请求】的方式及解决方案。

前端

ajax实现
1.POST JSON数据包

var requestData = {                        name: "xxx",      value: "xxxx",      now: new Date().getTime()  }var submit_sync = function() {  $.ajax({      type: "post",      url: 'http://chauncey.com',      async: false, // 使用同步方式      // 1 需要使用JSON.stringify 否则格式为 a=2&b=3&now=14...      // 2 需要强制类型转换,否则格式为 {"a":"2","b":"3"}      data: JSON.stringify(requestData),      //请求头部设置      contentType: "application/json; charset=utf-8",      dataType: "json",      success: function(data) {          $('#chauncey').text(data.msg);      }  });}

【HTTP请求部分内容】

    POST /test-jquery-ajax/add-post-json.php HTTP/1.1      Host: 192.168.1.104      Connection: keep-alive      Content-Length: 35      Accept: application/json, text/javascript, */*; q=0.01      X-Requested-With: XMLHttpRequest      Content-Type: application/json; charset=UTF-8      {"name": "xxx","value": "xxxx","now": 123123123}    【HTTP响应部分内容】    HTTP/1.1 200 OK    Content-Length: 13    Content-Type: application/json;charset=utf-8    {"result":46}

2.要点说明
【1】
需要使用 JSON.stringify 否则HTTP请求为a=12&b=34。
以下写法并不能达到POST JSON数据包的效果,这是标准的POST格式。
data: {
a: parseInt((input[name=a]).val()),b:parseInt((‘input[name=”b”]’).val()),
now: new Date().getTime() // 注意不要在此行增加逗号
},
【2】
需要强制类型转换 parseInt() ,否则HTTP请求为 {“a”:”12”,”b”:”34”}
以下代码并不能达到预期效果
data: JSON.stringify(dataObj);

后端

nodejs实现

在nodejs的后台开发中,经常会去调用其他服务器的接口,这个时候,就需要发送HTTP请求了。(chrome的postman插件很不错,对于前后端开发者都有很好的辅助作用)

以下操作均默认认为node环境已经搭建好。如需了解node环境搭建,点击这里
1.安装

//安装request,这里我们只讨论request模块实现npm install --save request

2.使用
1)GET请求,相对简单(DELETE类似)

var request = require('request');request('http://chauncey.com', function (error, response, body) {  if (!error && response.statusCode == 200) {    console.log(body) // Show the HTML for the baidu homepage.  }})

2)POST & PUT 类似
a. application/json

request({    //请求接口地址    url: url,    //请求类型    method: "POST",    json: true,    //请求头部设置    headers: {        "content-type": "application/json",    },    //需要转为字符串    body: JSON.stringify(requestData)}, function(error, response, body) {    if (!error && response.statusCode == 200) {    }});

b. application/x-www-form-urlencoded

request.post({url:'http://chauncey.com/upload', form:{key:'value'}}, function(error, response, body) {    if (!error && response.statusCode == 200) {    }})

c. multipart/form-data

//formData可以直接放key-value格式的数据,也可以放buffer,或者是通过流描述的文件var formData = {    // Pass a simple key-value pair    my_field: 'my_value',    // Pass data via Buffers    my_buffer: new Buffer([1, 2, 3]),    // Pass data via Streams    my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),};request.post({url:'http://chauncey.com/upload', formData: formData}, function (error, response, body) {      if (!error && response.statusCode == 200) {    }})

(1)更多 Nodejs Request使用介绍: 点这里
(流,表单, HTTP认证, OAuth登录, 定制HTTP header, cookies)
——这是request的GitHub主页

(2)nodejs原生自带http模块解决方案。点这里

后端body接收处理

后台处理express配合bodyParser处理请求

//引入var bodyParser = require('body-parser');var multer = require('multer'); //中间件使用app.use(bodyParser.json()); // for parsing application/jsonapp.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencodedapp.use(multer()); // for parsing multipart/form-data

总结

以上就是关于,前后端关于post请求中几种body数据格式实现方式,算是最近遇到的很多坑,因为headers中content-type等配置不同导致
0 0
原创粉丝点击