What is the correct way to send json POST request with Gnomes libsoup

606 views Asked by At

Im having trouble sending POST requests with Gnome's libsoup. GET requests I can do just fine I just am unsure how to get a working post request.

 _httpSession = new Soup.Session();

        let url = "http://localhost:3000/api/auth/register/org";
        var body = {body:"?how to add"}

        let message = Soup.Message.new('POST', url);

        message.set_request('application/json', 2,body);
        _httpSession.queue_message(message, function (_httpSession, message){
            //log res
            global.log(message.response_body.data)

        });

This is what I have right now. I don't know how to add the body of post request. The documentation says set_request requires 4 params but I get an error saying it expects 3 if I add the body.length.

2

There are 2 answers

0
ziegelesch On

Regarding the differing number of parameters, check if the documentation matches the used Soup-version:

log(`Soup version: ${Soup.get_major_version()}.${Soup.get_minor_version()}`);

Regarding the adding of the payload to your message, the string has to be transformed into a byte array (see here):

var body = `{"user":"tom","pass":"1234"}`;
const encoder = new TextEncoder();
message.set_request('application/json', 2, encoder.encode(body));
2
Roger Lee On

 _httpSession = new Soup.Session();

        let url = "http://localhost:3000/api/auth/register/org";
        var body = `{"user":"tom","pass":"1234"}`

        let message = Soup.Message.new('POST', url);

        message.set_request('application/json', 2,body);
        _httpSession.queue_message(message, function (_httpSession, message){
            //log res
            global.log(message.response_body.data)

        });

For anyone trying to figure this out the body has to be a string created to look like a json object. All of the examples I saw were just saying

body="user=this"

which is incorrect.