尽管主机、方法、内容类型设置正确,但 Poco 库 PUT 方法未按预期工作

Poco library PUT method not working as expected although host, method, content-type are set correctly

我在带有 Poco 库的 C++ 中有以下代码,应该在本地主机上执行 PUT,主体类似于 {"name" : "sensorXXX", "totalLots" : 50, "occupied": 5}

string url = String("http://localhost:3000/cam1111");
URI uri(url);
HTTPClientSession session(uri.getHost(), uri.getPort());

// prepare path
string path(uri.getPathAndQuery());
if (path.empty()) path = "/";

// send request
HTTPRequest req(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json");

string body = string("{\"name\" : \"Parking Sensor developed by aromanino\", \"totalLots\" : 50, \"occupied\": 5}");
// Set the request body
req.setContentLength( body.length() );

// sends request, returns open stream
std::ostream& os = session.sendRequest(req);
cout<<"request sent to " <<uri.getHost()<<endl;
cout<<"port "<<uri.getPort()<<endl;
cout<<"path "<<uri.getPathAndQuery()<<endl;
cout<<"body:\n"<<body<<endl;

HTTPResponse res;
cout << res.getStatus() << " " << res.getReason() << endl;

return 0;

它应该放在 NodeExpress 中完成的本地中间件上。

我收到 200 条回复,所以应该没问题。

但是中间件正在接收一些东西(因此主机和端口是正确的)但它没有执行我期望的终点:

router.put("/:dev", function(req, res){
    //console.log(req.params.dev);
    /*Check if request contains total and occupied in the body: If not reject the request.*/
    var stat;
    var body_resp = {"status" : "", "message" : ""};;
    console.log(req.body);
    ....
});

它也没有被 router.all('*', ...) 捕获。

相同的主机、正文、内容类型在 Postman 上按预期工作。

我应该在 Poco 库中设置什么才能执行正确的 PUT 请求。

您实际上并不是在发送带有 HTTP 请求的正文,如:

std::ostream& os = session.sendRequest(req);
os << body;

此外,您还必须在发送带有正文的请求后接收服务器响应 - 仅声明 HTTPResponse 对象是不够的。

HTTPResponse res;
std::istream& is = session.receiveResponse(res);

所以,完整的片段应该是:

string url = string("http://localhost:3000/cam1111");
URI uri(url);

HTTPClientSession session(uri.getHost(), uri.getPort());

string path(uri.getPathAndQuery());
if (path.empty()) path = "/";

HTTPRequest req(HTTPRequest::HTTP_PUT, path, HTTPMessage::HTTP_1_1);
req.setContentType("application/json");

string body = string("{\"name\" : \"Parking Sensor developed by aromanino\", \"totalLots\" : 50, \"occupied\": 5}");
req.setContentLength(body.length());

std::ostream& os = session.sendRequest(req);
os << body;

HTTPResponse res;
std::istream& is = session.receiveResponse(res);
cout << res.getStatus() << " " << res.getReason() << endl;