Nodejs – 用文件中的选项–data保留api调用

我正在从一个nodejs应用程序restAPI调用。

我的curl调用如下所示:

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) {...} 

您可以使用请求库来pipe理请求,如下所示:

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

或者,使用普通的Node.js,将文件asynchronous地读入内存 ,并且一旦加载完成,请求如下所示:

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