nodepp icon indicating copy to clipboard operation
nodepp copied to clipboard

show an example of an http client request with a POST method and a JSON body?

Open EDBCREPO opened this issue 2 years ago • 6 comments

🔗 u/Puzzled-Landscape-44

Question

Hi. Can you show an example of an http client request with a POST method and a JSON body? I can't seem to get it to work. All I get as a response is ERROR: Could not connect to server which is not true as the request is logged on the server side.

Answer

// Server.cpp

#include <nodepp/nodepp.h>
#include <nodepp/http.h>
#include <nodepp/json.h>

using namespace nodepp;

void onMain(){

    auto server = http::server([=]( http_t cli ){ 
        
        cli.write_header( 200, header_t({
            { "content-type", "text/html" }
        }));

        if( cli.method == "POST" ){
            console::log( cli.read() );
        }
        
        cli.write( "Hello World" );

    });

    server.listen( "0.0.0.0", 8000, [=]( socket_t server ){
        console::log("server started at http://localhost:8000");
    });

}
# Compile Server
- 🪟: g++ -o server server.cpp -I ./include -lws2_32 ; ./server
- 🐧: g++ -o server server.cpp -I ./include ; ./server
// Client.cpp

#include <nodepp/nodepp.h>
#include <nodepp/http.h>
#include <nodepp/json.h>

using namespace nodepp;

void onMain(){

    fetch_t args;
            args.method = "POST";
            args.url = "http://localhost:8000/";
            args.headers = header_t({
                { "Host", url::host(args.url) }
            });

            // Send String
            args.body = json::stringify( object_t({
                { "var1", 10 },
                { "var2", true },
                { "var3", "Hello World" },
            }) );

            // Send File Stream
            // args.file = file_t( "file.json", "r" );

    http::fetch( args )

    .then([]( http_t cli ){
        console::log( cli.read() );
    })

    .fail([]( except_t err ){
        console::error( err );
    });

}
# Compile Client
- 🪟: g++ -o client client.cpp -I ./include -lws2_32 ; ./client
- 🐧: g++ -o client client.cpp -I ./include ; ./client

EDBCREPO avatar Jul 24 '24 01:07 EDBCREPO

Thank you. This client example works fine with the provided server example. However, i get the same ERROR: Could not connect to server when connecting the NodePP client to basic servers written in other platforms. I have tried these ones:

// node node-server.js
const http = require('node:http')

http.createServer((req, res) => {
	res.write(JSON.stringify({ token: "abcdefg" }))
	res.end()
}).listen(8000)
// bun bun-server.js
Bun.serve({
	port: 8000,
	hostname: "localhost",
	fetch() {
		return new Response(JSON.stringify({ token: "abcdefg" }))
	}
})
# python python-server.py
from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        response = json.dumps({ "token": "abcdefg" })
        self.send_response(200)
        self.end_headers()
        self.wfile.write(json.dumps({ "token": "abcdefg" }).encode('utf-8'))

HTTPServer(('localhost', 8000), Handler).serve_forever()

I have confirmed that these all work with the following cURL request:

curl -H 'Content-Type: application/json' \
	-d '{ "username":"user","password":"pass"}' \
	-X POST http://localhost:8000/auth

russism avatar Jul 24 '24 02:07 russism

Yes, that was a bug, update the project and try again. Tell me if the problem persists. 👍

EDBCREPO avatar Jul 24 '24 05:07 EDBCREPO

Great! Working with the Python and NodeJS servers now, but not with BunJS. I'll try to investigate.

russism avatar Jul 24 '24 07:07 russism

Ok, it appears there is still a problem with args.body. The following server script prints the request body, but with the NodePP client the body is blank. An error response HTTP/1.1 400 Bad Request is also sent.

const http = require('node:http')

http.createServer((req, res) => {
	let body = '';
    req.on('data', chunk => {
        body += chunk.toString();
    });
    
    req.on('end', () => {
        console.log('Body:', body);

        res.setHeader('Content-Type', 'application/json');
        res.write(JSON.stringify({ token: "abcdefg" }));
        res.end();
    });
}).listen(8000)

russism avatar Jul 24 '24 07:07 russism

Yep, the problem was the Content-Length header. Update the project again and tell me if there is another bug. 👍

EDBCREPO avatar Jul 24 '24 13:07 EDBCREPO

Works perfect now. Thank you!

russism avatar Jul 25 '24 00:07 russism