V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
siwadiya

ajax 发送的 formdata,后台为什么收不到

  •  
  •   siwadiya · May 11, 2021 · 1965 views
    This topic created in 1811 days ago, the information mentioned may be changed or developed.

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

    <div id="app">
      <input type="file" name="" id="fileSelect" />
      <button type="submit" id="fileUpload">fileUpload</button>
    </div>
    <script>
      const fileSelect = document.getElementById('fileSelect');
      const fileUpload = document.getElementById('fileUpload');
      fileUpload.addEventListener('click', picUpload);
      function picUpload() {
        let formdata = new FormData();
        console.log('filelist: ', fileSelect.files);
        formdata.append('myfile', fileSelect.files[0]);
        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:3000', true);
        xhr.setRequestHeader('Content-Type', 'multipart/form-data');
        xhr.send(formdata);
      }
    </script>
    
    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 都是空的

    1 replies    2021-05-11 16:13:54 +08:00
    jay4497
        1
    jay4497  
       May 11, 2021
    把 setRequestHeader 那行去掉就行了。

    developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

    这里有段 warning 好像说的是这个。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   849 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 21:21 · PVG 05:21 · LAX 14:21 · JFK 17:21
    ♥ Do have faith in what you're doing.