技术解析

ajax 发送的 formdata,后台为什么收不到
0
2021-08-10 01:28:38
idczone

ajax 发送 formdata,用 formidable 来处理接收的数据,然后存到本地; 用 axios 发送的请求,可以正常运行,但是用原生 ajax 的就无效,是哪里写错了吗

const http = require('http'),
  formidable = require('formidable');
path = require('path');
const server = http.createServer(function (req, res) {
  if (req.method.toLowerCase() === 'post') {
    const form = formidable({
      multiples: true,
      uploadDir: path.resolve(__dirname, 'upload'),
    });

    form.parse(req, (err, fields, files) => {
      console.log('fields:', fields);
      console.log('files:', files);
      res.writeHead(200, {
        'content-type': 'application/json',
        'Access-Control-Allow-Origin': '*',
      });
      res.end(JSON.stringify({ fields, files }, null, 2));
    });
    return;
  }
  res.writeHead(200, {
    'content-type': 'text/html',
    'Access-Control-Allow-Origin': '*',
  });
  res.end('Done!');
});
server.listen(3000);

打印出来 fields 和 files 都是空的


把 setRequestHeader 那行去掉就行了。
developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
这里有段 warning 好像说的是这个。

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服