【问题标题】:Multipart/form-data sends empty data using axiosmultipart/form-data 使用 axios 发送空数据
【发布时间】:2022-02-18 22:56:40
【问题描述】:

我正在尝试提出请求,但是,我的身体似乎没有被发送。 我创建了一个 API,它返回的正是我发送的内容,但是正文返回的是空的。

注意事项:

  1. 通过 API,我需要发送 .txt 或 .msg 格式的文件。
  2. 我隐藏了下面的一些信息,因为这很敏感 业务数据。
const axios = require('axios');

async function UploadFile(urlNovaTarefa, siteUrl, clientId, clientSecret, nomeCentral, grupoId, AssuntoId, usuario, solicitante, copia, solicitacao, anexoNome, anexoConteudo, dataEntrada, enviarNotificacao, cnpjPedido, responsavel){
    // formData
    const form = new FormData();
    form.append('NomeCentral', nomeCentral);
    form.append('GrupoId', grupoId);
    form.append('AssuntoId', AssuntoId);
    form.append('Usuario', usuario);
    form.append('Solicitante', solicitante);
    form.append('Copia', copia); 
    form.append('Solicitacao', solicitacao);
    form.append('AnexoNome', anexoNome);
    form.append('AnexoConteudo', anexoConteudo);
    form.append('DataEntrada', dataEntrada);
    form.append('EnviarNotificacao', enviarNotificacao);
    form.append('CNPJPedido', cnpjPedido);
    form.append('Responsavel', responsavel);

    //console.log(form);
    
    let response = await axios.post(urlNovaTarefa, form, {
          headers: {
            'SiteUrl': siteUrl,
            'Client-Id': clientId,
            'Client-Secret': clientSecret,
            'Content-Type': "multipart/form-data; boundary=CSC",
            'Access-Control-Allow-Origin': "*",
          },
        });

        let data = response.data;
        console.log(data);
  }


  UploadFile("https://example.net/ct/csc/novaTarefa", "https://example.com/sites/centralcsc/", "1234-1234-1234-1234", "abcd-abcd-abcd-abcd=", "ServicosClientes", "4", "3", "email@example.com", "email@example.com", "email@example.com", "Test", "Test.txt", "C:\\Users\\User\\Desktop\\Test.txt", "07/10/2021 14:30", "N", "[{\"NumeroCNPJ\":\"12345678910112\",\"NumeroPedido\":[]}]", "email@example.com")
  .then(response => console.log(response))
  .catch(err => console.log(err))

应该在我的身体上发送的内容(表单数据)是这样的:

  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="NomeCentral"\r\n' +
    '\r\n',
  'ServicosClientes',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="GrupoId"\r\n' +
    '\r\n',
  '4',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="AssuntoId"\r\n' +
    '\r\n',
  '3',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="Usuario"\r\n' +
    '\r\n',
  'email@example.com',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="Solicitante"\r\n' +
    '\r\n',
  'email@example.com',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="Copia"\r\n' +
    '\r\n',
  'email@example.com',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="Solicitacao"\r\n' +
    '\r\n',
  'Test',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="AnexoNome"\r\n' +
    '\r\n',
  'Test.txt',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="AnexoConteudo"\r\n' +
    '\r\n',
  'C:\\Users\\User\\Desktop\\Test.txt',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="DataEntrada"\r\n' +
    '\r\n',
  '07/10/2021 14:30',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="EnviarNotificacao"\r\n' +
    '\r\n',
  'N',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="CNPJPedido"\r\n' +
    '\r\n',
  '[{"NumeroCNPJ":"12345678910112","NumeroPedido":[]}]',
  [Function: bound ],
  '----------------------------553386948041586350665922\r\n' +
    'Content-Disposition: form-data; name="Responsavel"\r\n' +
    '\r\n',
  'email@example.com',
  [Function: bound ]
]

这是我的 API 的回报! 身体是空的。

 Resultado: 0,
 Mensagem: 'Success',
 Headers: {
   connection: 'Keep-Alive',
   'transfer-encoding': 'chunked',
   accept: 'application/json, text/plain, */*',
   host: 'example.net',
   'max-forwards': '10',
   'user-agent': 'axios/0.23.0',
   'x-client-ip': '000.00.00.000',
   'x-client-port': '00000',
   siteurl: 'https://example.com/sites/centralcsc/',
   'client-id': '1234-1234-1234-1234',
   'client-secret': 'abcd-abcd-abcd-abcd=',
   'access-control-allow-origin': '*',
   'x-waws-unencoded-url': '/ct/csc/novaTarefa',
   'client-ip': '000.00.00.000:00000',
   'x-arr-log-id': 'xxxxxxxxxxxxxxxxxxxx',
   'disguised-host': 'example.net',
   'x-site-deployment-id': 'example',
   'was-default-hostname': 'example.net',
   'x-original-url': '/ct/csc/novaTarefa',
   'x-forwarded-for': '000.00.00.000:00000',
   'x-arr-ssl': '2048|256|C=US, O=Microsoft Corporation, CN=Microsoft RSA TLS CA 02|CN=*.example.net',
   'x-forwarded-proto': 'https',
   'x-appservice-proto': 'https',
   'x-forwarded-tlsversion': '1.2',
   'request-id': '|999999999-99999999999999.1.',
   'content-type': 'multipart/form-data; boundary=CSC'
 },
 Body: {}
}
undefined

【问题讨论】:

    标签: node.js api rest axios multipartform-data


    【解决方案1】:

    我遇到了同样的问题。我花了一整天的时间来修复它,但最后我只是将我的 Axios 版本降级到 ^0.21.4 它开始像魅力一样工作。问题是 Axios 最新版本的错误。

    【讨论】:

      【解决方案2】:

      嗨 ? 欢迎来到 StackOverflow!

      我不认为你的代码是错误的,只是你的“我创建了一个 API 可以准确地返回我发送的内容”可能不正确......如果你搜索对于“post bin”,您会发现很多免费服务会为您提供一个临时 URL,以便您可以发送数据并检查它

      其中一项服务是https://hookbin.com/

      我刚刚根据您的问题创建了一个非常简单的代码:

      const axios = require('axios');
      const FormData = require('form-data');
      
      async function UploadFile(dataToUpload) {
         const { clientId, clientSecret } = dataToUpload;
          
         const form = new FormData();
         Object.keys(dataToUpload).forEach(key => form.append(key, dataToUpload[key]));
      
         const response = await axios({
            method: 'POST',
            url: 'https://hookb.in/nPDl9aLjgVsZ7Qrr7ja6',
            data: form,
            headers: {
               ...form.getHeaders(),
               'Client-Id': clientId,
               'Client-Secret': clientSecret,
            },
         });
      
         console.log(response.data);
      }
      
      
      (async () => {
          await UploadFile({
              clientId: '1234',
              clientSecret: 'abc',
              nomeCentral: 'ServicoClientes',
              grupoId: '4',
              assuntoId: '5',
              usuario: 'email@example.com',
              solicitante: 'email@example.com',
              copia: 'email@example.com',
              solicitacao: 'teste',
              dataEntrada: '07/10/2021 14:30',
              enviarNotificacao: 'N',
              cnpjPedido: '[{\"NumeroCNPJ\":\"12345678910112\",\"NumeroPedido\":[]}]',
              responsavel: 'email@example.com'
          })
      })();
      

      注意上面的代码和下面是一样的,代码风格只是个人喜好

      await axios.post('https://hookb.in/nPDl9aLjgVsZ7Qrr7ja6', form, {
        headers: {
           ...form.getHeaders(),
           'Client-Id': clientId,
           'Client-Secret': clientSecret,
        },
      });
      

      Hookbin 确实显示了所有的 data in the body


      只是给你一些关于如何改进你的代码的提示:

      • 函数应该接受最多 3 个输入,除此之外,尝试传递一个对象作为输入,因为这样会更容易阅读并知道函数需要什么(如果使用 typescript 会更好)
      • 每次重复行时,请尝试想出一些更简单的方法,在您的示例中,请参阅我的 forEach 循环,我只用一行发送 1 或 50 个属性
      • 将日期作为整数发送并将其保存在数据库中而不是格式化日期更容易,因为数据库可能位于不同的国家/地区,您将开始遇到转换问题,请尽可能尝试发送,例如: dataEntrada: Date.now()
      • 与布尔值相同,enviarNotificacao: 'N' 最好发送为 enviarNotificacao: false,因为如果您需要在数据库中索引该值,它会更容易和更快
      • 请记住form.getHeaders()会自动在请求上附加正确的headers,无需指定更多,查看链接中的headers或下图(以防链接过期)

      【讨论】:

        猜你喜欢
        • 2021-12-09
        • 2013-04-09
        • 2012-10-01
        • 2021-01-07
        • 1970-01-01
        • 2018-04-08
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        相关资源
        最近更新 更多