brino
July 4, 2018, 9:32am
#1
Hey,
I’m not sure if there is something wrong with my code but I am trying to send a POST request to my server and the server (nodeJs) receives a PUT request.
Here is the code I am using:
ofURLFileLoader http;
ofHttpRequest request;
request.method = ofHttpRequest::POST;
request.timeoutSeconds = 3;
request.url = config["server"]["address"].get<string>() + "/api/someTest";
request.contentType = "application/json";
ofJson content;
content["some_id"] = id;
content["terminal_id"] = config["server"]["id"].get<string>();
request.body = content.dump();
auto response = http.handleRequest(request);
if (response.status != 200) ofLogError("RfidT::sendBandId", "server is not answering");
The server then receives
PUT /api/someTest
The issue should be in the of application since the POST request works when sending from other instances (Firefox etc.).
So, am I doing something wrong, or is there some of issue and should I better use ofxhttp (but just for doing a request it would be a bit over engineered)?
Thanks in advance!
1 Like
brino
July 5, 2018, 1:57pm
#2
Thanks to @underdoeg ( post ) I could solve it by using libcurl directly:
ofHttpResponse Utils::sendPostRequest(string url, ofJson content)
{
ofHttpResponse response;
CURLcode ret;
CURL *hnd;
struct curl_slist *slist1;
std::string jsonstr = content.dump();
slist1 = NULL;
slist1 = curl_slist_append(slist1, "Content-Type: application/json");
hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_URL, url.c_str());
curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, jsonstr.c_str());
curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.38.0");
curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);
//response
curl_easy_setopt(hnd, CURLOPT_TIMEOUT, 3);
ret = curl_easy_perform(hnd);
if (ret == CURLE_OK) {
long http_code = 0;
curl_easy_getinfo(hnd, CURLINFO_RESPONSE_CODE, &http_code);
response.status = http_code;
} else {
response.error = curl_easy_strerror(ret);
response.status = -1;
}
curl_easy_cleanup(hnd);
hnd = NULL;
curl_slist_free_all(slist1);
slist1 = NULL;
return response;
}
1 Like