简体   繁体   English

使用node.js的简单Post formData和请求保持失败

[英]Simple Post formData with node.js and request keep failing

I am trying to post data with a file to remote server using node.js and request module, the code send the data without the file. 我正在尝试使用node.js和请求模块将带有文件的数据发布到远程服务器,代码发送没有文件的数据。 I use the docs example https://github.com/request/request#forms 我使用文档示例https://github.com/request/request#forms

I can post the same data with php curl with the code below , so I know the remote server code works. 我可以使用下面的代码通过php curl发布相同的数据,因此我知道远程服务器代码有效。

What am I doing wrong? 我究竟做错了什么?

$post = array(
    'sessionId' => 1234,
    'source' => 'text',
    'files[jpg]' => '@' . $file_name_with_full_path
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
curl_close($ch);

My node.js code 我的node.js代码

var fs = require("fs");
var formData = {
    sessionId: 1234,
    source: 'text',
    files: JSON.stringify (
              {jpg:  fs.createReadStream( __dirname +"/"+ file.txt)}
      )
  request.post({url: 'https://url', formData: formData}, 
    function optionalCallback(err, httpResponse, body) {

    });

This code successfully posted the file. 此代码成功发布了文件。

  var r = request.post('https://url', function optionalCallback(err,httpResponse, body) { })
    var form = r.form();
    form.append('sessionId', 1234);
    form.append('source', 'text');
    form.append('file[jpg]', fs.createReadStream( __dirname +"/"+ file.txt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM