gpt4 book ai didi

node.js - Nodejs - 使用选项--来自文件的数据进行 Rest api 调用

转载 作者:搜寻专家 更新时间:2023-11-01 00:38:10 26 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用 request库来管道这样的请求:

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

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

或者,使用普通的 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();
}

关于node.js - Nodejs - 使用选项--来自文件的数据进行 Rest api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44277259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com