js post FormData、Payload、multipart/form-data数据,Nodejs获取multipart/form-data数据

1、post数据结构:

Request Payload

------WebKitFormBoundary3wELd4ULBH0cBXBj
Content-Disposition: form-data; name="type"

post
------WebKitFormBoundary3wELd4ULBH0cBXBj
Content-Disposition: form-data; name="name"

post发送formData参数
------WebKitFormBoundary3wELd4ULBH0cBXBj--

 

   // form 方式提交

<form method="post" encType="multipart/form-data">

....

</form>

  

 

2、js代码实现

var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/post', true);

var formData = new FormData();
for (var key in data) {
  formData.append(key, data[key]);
}
xhr.send(formData);

xhr.onload = function () {
  if (xhr.status === 200) {
    var text = xhr.responseText;
    if (success) success(JSON.parse(text));
  } else {
    if (error) error(xhr);
  }
};

 js post FormData、Payload、multipart/form-data数据,Nodejs获取multipart/form-data数据_第1张图片

 

3、后端获取数据(Nodejs)

var express = require('express');
var app = express();
var multipart = require('connect-multiparty');

var multipartMiddleware = multipart();
app.post('/post', multipartMiddleware, function(req, res) {
  res.header('Access-Control-Allow-Origin', '*');

  console.log('get FormData Params: ', req.body);

  res.json({result: 'success', data: req.body});
});

 

你可能感兴趣的:(众观千象,每天进步一点点,学习永无止境,FormData,乔乐共享)