【问题标题】:Unable to receive axios request object无法接收axios请求对象
【发布时间】:2021-09-01 10:18:19
【问题描述】:

我正在尝试使用 axios 发送一个包含多个文件和输入字段的 JSON 数组。 处理文件和后续字段,最后尝试发送如下对象:

[
  {file : "",
   text : ""
  }, {...}, {...}
]

ServerA.js

const bodyParser = require('body-parser');
const multer  = require('multer');
const upload = multer();

app.use(bodyParser.json()); 
app.use(upload.any());

app.post('/requestFile',(req,res) => {
let files = req.files;
let textInfo = req.body;
let form = [];
files.forEach((file,index)=>{
    let formObj = {};
    formObj.file = file;
    let key = Object.keys(textInfo)[index];
    let value = texInfo[key];
    formObj.text = value;
    form.push(formObj)
})
axios.request({
    method: 'post',
    url: `http://localhost:1001/receiveFiles`,
    headers: {
        'Content-Type': 'multipart/form-data'
    },
    data: {
        form
    }
}).then(response => {
    res.send('No Err');
}).catch(err=>{
    res.send('ERR')
})
})

但是当我尝试在接收端打印正文时得到一个空对象:

ServerB.js

app.use(bodyParser.json()); 
app.use(upload.any());

app.post('/receiveFiles', (req,res) => {
console.log("Print: " + JSON.stringify(req.body));
res.send('successful');
})

我得到以下结果:

Print : {}

我是 Nodejs 新手,如果有人能帮助我,那就太好了

【问题讨论】:

  • 当您从另一个端点调用receiveFiles 时,您无法判断代码的哪一部分存在错误。尝试使用 curl、邮递员等方式致电您的 receivesFiles

标签: javascript node.js api axios


【解决方案1】:

这是您可以根据需要进行调整的代码。正如我在评论中告诉你的那样,使用调用另一个端点的文件调用端点......这不容易调试。

只需将所有这些代码(服务器+客户端)放入名为app.js的同一个文件中,并在安装所需的包后运行node app.js(不要安装fs它是一个内置的节点)

服务器部分

const app = express();
const multer  = require('multer');
const upload = multer();

app.use(upload.any());

app.post('/receiveFiles', (req,res) => {
    console.log("Receiving:", JSON.stringify(req.body) );
    console.log("Files are:", req.files);
    res.send('successful');
});

app.listen(3000, () => {
    console.log("Started");

    tryIt();
});

客户端部分

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');

const formData = new FormData();
formData.append('id', 1343);
formData.append('this file', fs.createReadStream('./app.js'));

function tryIt() {
    console.log("Calling the endpoint");

    const fullReq = {
        method: 'post',
        url: `http://localhost:3000/receiveFiles`,
        headers: formData.getHeaders(),
        data: formData
    };

    console.log('Req to be sent', fullReq);
    axios.request(fullReq).then(response => {
        console.log("data", response.data);
        console.log("status", response.status, response.statusText);
    }).catch(err=>{
        console.error(err);
    })
}

预期结果

Calling the endpoint
Req to be sent {
  method: 'post',
  url: 'http://localhost:3000/receiveFiles',
  headers: {
    'content-type': 'multipart/form-data; boundary=--------------------------224414152569192710241525'
  },
  data: FormData {
    _overheadLength: 266,
    _valueLength: 4,
    _valuesToMeasure: [ [ReadStream] ],
    writable: false,
    readable: true,
    dataSize: 0,
    maxDataSize: 2097152,
    pauseStreams: true,
    _released: false,
    _streams: [
      '----------------------------224414152569192710241525\r\n' +
        'Content-Disposition: form-data; name="id"\r\n' +
        '\r\n',
      '1343',
      [Function: bound ],
      '----------------------------224414152569192710241525\r\n' +
        'Content-Disposition: form-data; name="this file"; filename="app.js"\r\n' +
        'Content-Type: application/javascript\r\n' +
        '\r\n',
      [DelayedStream],
      [Function: bound ]
    ],
    _currentStream: null,
    _insideLoop: false,
    _pendingNext: false,
    _boundary: '--------------------------224414152569192710241525'
  }
}
Receiving: {"id":"1343"}
Files are: [
  {
    fieldname: 'this file',
    originalname: 'app.js',
    encoding: '7bit',
    mimetype: 'application/javascript',
    buffer: <Buffer 63 6f 6e 73 74 20 65 78 70 72 65 73 73 20 3d 20 72 65 71 75 69 72 65 28 27 65 78 70 72 65 73 73 27 29 3b 0a 63 6f 6e 73 74 20 61 70 70 20 3d 20 65 78 ... 1066 more bytes>,
    size: 1116
  }
]
data successful
status 200 OK

【讨论】:

    【解决方案2】:

    要在 Node.js 中使用 axios 发送文件,您需要:

    1. 使用表单数据库创建表单
    2. 使用 getHeaders() 从表单设置请求标头

    将您的代码更改为:

    const FormData = require('form-data');
    
    // ...
    
    app.post('/requestFile', (req, res) => {
      const files = req.files;
      const textInfo = req.body;
      
      // Construct form and append files and other data to it
      const form = new FormData();
      files.forEach((file, index) => {
        form.append('file', file, file.originalname);
    
        const key = Object.keys(textInfo)[index];
        form.append('text', textInfo[key]);
      });
    
      // Send form with axios and pass form boundary to the request header
      axios.post('http://localhost:1001/receiveFiles', form, {
        headers: {
          ...form.getHeaders(),
        },
      })
      .then(() => { ... });
    });
    

    然后在接收端:

    app.post('/receiveFiles', upload.array('file'), (req, res) => {
      const files = req.files; // [{ file1 }, { file2 }, ...]
      const data = req.body; // { text: ['textInfoFile1', 'textInfoFile2', ....] 
    });
    

    如需深入解释,请查看这篇文章Send a File With Axios in Node.js。它涵盖了一些常见的陷阱,您将学习如何发送存储为 Buffer 或来自 Stream 的文件。

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2022-01-18
      • 2015-12-29
      • 2021-02-03
      • 2019-01-06
      相关资源
      最近更新 更多