2017-05-31 57 views
7

我正在從一個nodejs應用程序休息API調用。Nodejs - 使用選項休息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文件,該文件在捲曲電話是--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) {...} 

回答

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

請問這還需要類似:常量FS =要求(「FS」); – Tarun

+1

我已經更新了我的答案 – Tom

+0

你可以請更改文件路徑,因爲沒有「。」。它可能會混淆某人! fs.createReadStream( '/ pipeline.json')。謝謝您的幫助 – Tarun