我在我的服务器上尝试 POST JSON,但它不起作用。当我发布时,服务器是空的并且没有文件。
如何正确POST?
CURL *curl;
string data;
CURLcode res;
std::ifstream myfile;
myfile.open("test_4.json");
string content( (istreambuf_iterator<char>(myfile) ),
(istreambuf_iterator<char>() ) );
curl = curl_easy_init();
string l="filedata=";
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "my_server");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, l+content);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
我还有 python 代码可以运行
pp=requests.post("my_server",data={"filedata":response})
我的服务器上的 POST js 代码(我无法更改)
app.post("/api/arch_base",jsonParser,function(req,res){
if(!req.body) return res.sendStatus(400);
const fdata=req.body.filedata;
console.log(fdata);
const collection = req.app.locals.collection;
collection.find({}).toArray(function(err,arch_data){
if(err) return console.log(err);
if(arch_data.length>0)
{
let id=arch_data[0]._id;
collection.findOneAndUpdate({_id:id},{$set: {FileData:fdata}},{returnOriginal:false},function(err,result){
if(err) return console.log(err);
});
}
});
haveUpdates=true;
});
最佳答案
libcurl 是 C 语言,而不是 C++。它需要 char*
,而不是 std::string
。
同样来自https://curl.se/libcurl/c/CURLOPT_POSTFIELDS.html :
The data pointed to is NOT copied by the library: as a consequence, it must be preserved by the calling application until the associated transfer finishes. This behavior can be changed (so libcurl does copy the data) by setting the CURLOPT_COPYPOSTFIELDS option.
您还需要设置 CURLOPT_POSTFIELDSIZE,因为 CURLOPT_POSTFIELDS 仅提供指针。
另外,我确定您得到的是“filedata=
关于c++ - 使用 C++curl 进行 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68225219/