gpt4 book ai didi

javascript - 使用npm的request包,你应该如何传递最初保存在文件中的数据?

转载 作者:行者123 更新时间:2023-12-01 01:13:35 24 4
gpt4 key购买 nike

我正在使用 npm 的请求,并且正在使用 API。通过 CURL 的 API 请求要求我使用 @site.json 通过文件发送信息。

示例:

curl -X POST -d @site.json 'https://api.xxxxxxx.com/site?id=123456’

这是我的代码的主要部分:

let data = JSON.stringify(`{"placement":{"name":"${placementName}"}}`);

fs.writeFile('placement.json', JSON.parse(data), (err, data) => {
if (err) console.log(err);
})

fs.createReadStream('placement.json').pipe(request(options));
// clear the file for next placement
fs.truncate('placement.json', 0, () => {console.log('done')})

因此,我能够使用此代码和我创建的函数来构建我需要的内容,以确保不会创建重复项。问题是我需要多次运行脚本才能构建所有“展示位置”。

我猜这是 fs 包,它运行速度不够快,或者有时无法写入文件。我可以看到 .json 文件,有时数据没有被清除(而是被覆盖),有时代码没有在应该更新的时候更新。

如果这个 json 数据最初包含在文件中,有没有办法通过使用“request”来传递它?我搜索了文档但还没有找到答案。

我在选项中尝试了几种方法,例如使用 json、数据、表单,但 API 似乎无法识别以这种方式发送的信息。我应该尝试其他方法吗?

我的选择:

const options = {
url: `https://api.xxxxxxxxxx.com/placement?id=${publisherId}`,
method: 'POST',
headers: {
'Authorization': token
}
};

谢谢

最佳答案

fs.writeFile 是异步函数,这意味着如果您想使用该文件,您需要在其回调中执行此操作,该回调在文件写入磁盘后调用,这就是您的位置if (err) console.log(err);.

但我认为您根本不需要将文件写入磁盘。

您可以直接将数据传递给请求,如下所示:

var request = require('request');

const options = {
url: `https://api.xxxxxxxxxx.com/placement?id=${publisherId}`,
method: 'POST',
headers: {
'Authorization': token
},
json: true,
body: { placement: { name: placementName } }
};

request(options, function callback(error, response, body) {
//...
});

不过我还没有尝试过代码。

关于javascript - 使用npm的request包,你应该如何传递最初保存在文件中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54955661/

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