Nodejs - 使用文件中的选项--data来调用api调用

时间:2017-05-31 06:29:31

标签: node.js rest curl

我正在从nodejs应用程序进行rest api调用。

我的卷曲调用看起来像这样:

curl -X PUT -iv -H "Authorization: bearer <token>" -H "Content-Type: application/json" -H "Accept: application/json" -H "X-Spark-Service-Instance: <spark-instance>" --data "@pipeline.json" -k https://<url>

我想在Nodejs中进行类似的调用。我无法理解如何发送一个json文件中的数据,该文件在curl调用中是--data "@pipeline.json".

我的Nodejs代码如下所示:

var token = req.body.mlToken;
var urlToHit = req.body.url;
var SPARKINSTANCE = req.body.sparkInstance;
var b = "bearer ";
var auth = b.concat(token); 


var headers = {
    'Content-Type': 'application/json',
    'Authorization': auth,
    'Accept': 'application/json',
    'X-Spark-Service-Instance': SPARKINSTANCE
}

var options= {
    url: urlToHit,
    method: 'PUT',
    headers: headers
}

console.log(urlToHit);
request(options, callback);
function callback(error, response, body) {...}

1 个答案:

答案 0 :(得分:3)

您可以使用request库来管道请求,如下所示:

var fs = require('fs');     
var options= {
    url: urlToHit,
    method: 'PUT',
    headers: headers
}

fs.createReadStream('./pipeline.json')
  .pipe(request.put(options, callback))

或者,使用普通的Node.js,将文件异步读入内存,然后加载一次,发出这样的put请求:

var fs = require('fs'); 
// Will need this for determining 'Content-Length' later
var Buffer = require('buffer').Buffer   

var headers = {
    'Content-Type': 'application/json',
    'Authorization': auth,
    'Accept': 'application/json',
    'X-Spark-Service-Instance': SPARKINSTANCE
}

var options= {
    host: urlToHit,
    method: 'PUT',
    headers: headers
}

// After readFile has read the whole file into memory, send request
fs.readFile('./pipeline.json', (err, data) => {
  if (err) throw err;
  sendRequest(options, data, callback);
});

function sendRequest (options, postData, callback) {  
  var req = http.request(options, callback);

  // Set content length (RFC 2616 4.3)
  options.headers['Content-Length'] = Buffer.byteLength(postData)

  // Or other way to handle error
  req.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
  });

  // write data to request body
  req.write(postData);
  req.end();
}