nodejs-带有选项的REST API调用-DATA来自文件



我正在从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中有类似的呼叫。我无法理解如何在curl调用中发送的json文件中发送的数据为 --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) {...}

您可以使用请求 PIPE 请求:

var fs = require('fs');     
var options= {
    url: urlToHit,
    method: 'PUT',
    headers: headers
}
fs.createReadStream('./pipeline.json')
  .pipe(request.put(options, callback))

或,使用plain node.js,将文件读取到内存异步和曾经加载的,请这样做:

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();
}

最新更新