logo elektroda
logo elektroda
X
logo elektroda

Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body

p.kaczmarek2 3207 0
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
📢 Listen (AI voice):
  • Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    Recently, I was running a simple system for reporting energy measurements via a WiFi network from a "smart" electrical outlet and I needed a convenient way to test the reception of HTTP GET and POST requests. I will show here how you can use Node.js for this purpose. Node.js allows you to quickly and efficiently set up a mini-HTTP server on our machine, capable of processing these queries and responding to them in the way we specify. By the way, I will also show how you can handle a POST query with content in JSON format and I will put here short examples of sending GET and POST from the OpenBeken
    NOTE: The topic assumes that the reader has at least minimal knowledge of how to use the console, how to install Node.js, what is the server, HTTP, and so on...

    Sending HTTP requests
    In this topic, I assume that we already have the code for sending requests (i.e. the client), and we need to create a mini server for testing, but it is still worth highlighting how these requests can be sent.
    For example, you can use a library curl which is available on multiple platforms:
    https://curl.se/
    Another way may be to send directly from Javascript, even if executed in the browser, we can create an HTML file and play with it XMLHttpRequest be fetch and so on.
    Yet another, extremely complicated way is to send queries from your own environment, for example, at my place OpenBeken there are functions to send GET and POST, these are the functions I tested when creating this theme.
    Regardless of the choice of the client, in this topic I will show you how to create a simple HTTP server in Node.js, capable of receiving the mentioned GET and POST.

    HTTP GET support
    The GET query is probably the most popular on the web, it allows you to encode arguments in the URL of the page itself, even on our forum when writing a post we see:
    
    https://www.elektroda.pl/rtvforum/posting.php?mode=reply&t=3977701&p=20578056
    

    The GET arguments are after the question mark, we can see here that the "mode" key is "reply" and the "t" key is "3977701", etc.
    As an example, we'll make a simple calculator. As arguments will be a and b, the server will return their sum to us. We create the server.js file and save:
    Code: Javascript
    Log in, to see the code

    Calling app.get in the code above is not sending a GET request, but creating a callback that will handle it. In it we receive and process data. By req.query we're getting the arguments from the URL.
    We navigate in CMD to the folder where the script is, and run it via nodeserver.js , but we will probably get an error - there is no package express , you need to install it via npm install express here is the whole log:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    Then already nodeserver.js is performed correctly.
    Now you need to somehow send data to it , method one - browser, open the URL:
    
    http://127.0.0.1:3000/?a=13&b=87
    

    Works:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    In the server log we also see that something is going on:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    Now let's send a GET request via CURL:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    Of course, CURL must be installed beforehand.

    And as a curiosity - the same with OpenBeken:
    
    backlog setChannel 10 13; setChannel 11 87; SendGET http://localhost:3000/?a=$CH10&b=$CH11
    

    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    In OBK, this mechanism does not yet support parsing responses from the script level, it is only used to report data to the server.

    HTTP POST support
    Now it will be a bit more difficult, because the POST content is already contained in the body of the query, not in the URL, so it is basically invisible at first glance. Of course, POST also occurs even on our forum, for example, when we log in or register, then our login and password are sent with a POST query.
    The post additionally introduces the so-called Content-Type , i.e. the type of query content, it can be, for example, plain text, binary stream or just JSON format.
    What does JSON look like? Sample JSON below:
    Code: JSON
    Log in, to see the code

    JSON can store objects along with key-value pairs and arrays.
    As an example, let's rewrite our code so that it uses JSON format but still performs the same operation.
    Code: Javascript
    Log in, to see the code

    As before, we created a callback in app.get , here we create the post service in the same way app.post . Now we take a and b from the text in JSON format, from the body of the query.
    Now you have to test it. Let's start with the CURL method:
    
    curl -X POST -H "Content-Type: application/json" -d "{\"a\": 13, \"b\": 87}" http://localhost:3000/
    

    Switch X sets the query type, H adds a Content-Type header specifying what we send, -d sets the data. Quotation marks with \ are so-called escape sequence, allows you to put quotation marks in the body of the query without actually closing the quotation marks specifying the block of data.
    Everything works:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    As an example, let's see how the same can be sent from Javascript itself - from a simple HTML file, run in the browser, without setting up a server. Anyone can easily fire it:
    Code: HTML, XML
    Log in, to see the code

    Unfortunately, this script will not execute correctly. There is a problem with CORS (Cross-Origin Resource Sharing) here.
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    Error content as text:
    
    p://localhost:3000/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
    test.html:18 
          
            POST http://localhost:3000/ net::ERR_FAILED
    sendSumRequest @ test.html:18
    onclick @ test.html:23
    

    CORS is blocking external Ajax requests to make resources more secure, we need to unblock them. We modify the server:
    Code: Javascript
    Log in, to see the code

    We are not firing yet, otherwise we would get an error:
    
    Error: Cannot find module 'cors'
    

    so we install the missing package:
    
    npm install cors
    

    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    After this change (and server restart) the script works:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    And as a curiosity, the same with OpenBeken:
    
    backlog setChannel 10 13; setChannel 11 87; SendPOST http://localhost:3000/ 3000 "application/json" "{ \"a\":$CH10, \"b\":$CH11 }"
    

    The code specifically, as part of the demonstration, sets the channels to 13 and 87 and then uses their values when generating JSON.
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body
    Result:
    Node.js as a mini HTTP server, testing GET and POST queries, JSON, express, body

    Summary
    Node.js offers a very convenient collection of tools and libraries for building server-side applications in Javascript. Here I showed how they can be used to create a mini-server for testing the reception of GET and POST requests, because ultimately I intend to put the server on one of the free web hosting available on the web and the requests themselves will be received at the PHP level, but nothing stands in the way of use Node.js differently, all at your discretion.
    In a similar way, you can also access a database directly, e.g. InfluxDB, by using their HTTP API:
    https://archive.docs.influxdata.com/influxdb/v1.2/guides/writing_data/
    Perhaps soon I will show a specific example of implementing a temperature or voltage/current/power logger based on the mechanisms shown here.

    Cool? Ranking DIY
    Helpful post? Buy me a coffee.
    About Author
    p.kaczmarek2
    Moderator Smart Home
    Offline 
    p.kaczmarek2 wrote 14743 posts with rating 12839, helped 659 times. Been with us since 2014 year.
  • ADVERTISEMENT
📢 Listen (AI voice):

FAQ

TL;DR: Use Node.js on port 3000 as a mini HTTP server; “app.get is a callback,” not a sender. This FAQ helps IoT and OpenBeken users test GET parameters, JSON POST bodies, curl, browser requests, CORS, Express, and body parsing. [#20593560] Why it matters: A local Express server gives smart-outlet projects a fast, repeatable target before moving measurement logging to PHP, InfluxDB, or hosting.

Method Data location Example endpoint or command Main test use
GET URL query string /?a=13&b=87 Quick parameter tests
POST JSON Request body Content-Type: application/json Structured telemetry payloads
Browser/XHR Request body XMLHttpRequest to localhost:3000 Client-side Ajax test
OpenBeken Channel values SendGET / SendPOST Smart outlet reporting

Key insight: Build the smallest server that proves receipt, parsing, and response. For browser POST tests, enable CORS deliberately and restart the server after installing cors.

Quick Facts

  • The demo Express server listens on TCP port 3000 and accepts local requests such as http://127.0.0.1:3000/?a=13&b=87. [#20593560]
  • The GET calculator reads a=13 and b=87 from req.query, then returns the sum 100. [#20593560]
  • The JSON POST example uses Content-Type: application/json and a body shaped like { "a": 13, "b": 87 }. [#20593560]
  • Missing packages stop startup with errors such as Cannot find module 'cors'; install them with npm install express or npm install cors. [#20593560]
  • OpenBeken examples set channel 10 to 13 and channel 11 to 87, then report those values with SendGET or SendPOST. [#20593560]

How do I create a simple Node.js mini HTTP server with Express for testing GET and POST requests?

Create server.js, import express, create app, add parsers, then listen on port 3000.
  1. Install packages with npm install express and, if needed, npm install cors.
  2. Define handlers with app.get('/', ...) or app.post('/', ...).
  3. Start the script and send test requests to localhost:3000.
The thread uses this setup to test smart outlet HTTP reporting before moving data handling elsewhere. [#20593560]

How can I handle HTTP GET query parameters in Express and return a calculated result?

Read GET parameters from req.query, convert them, validate them, and return the calculated sum. The example uses a and b, parses both with parseInt, and rejects invalid input with HTTP status 400. With a=13 and b=87, the server logs the request and returns 100. The handler runs through app.get('/', ...), which receives requests rather than sending them. [#20593560]

How do I send a GET request with parameters to a local Node.js server using a browser or curl?

Send the parameters in the URL after the question mark. In a browser, open http://127.0.0.1:3000/?a=13&b=87. With curl, call the same URL from the console after installing curl. The Express server reads a and b from req.query, calculates 13 + 87, and returns the result as plain text. [#20593560]

How can OpenBeken SendGET be used to report channel values to a Node.js HTTP server?

Use OpenBeken SendGET with channel substitutions in the query string. The thread sets channel 10 to 13 and channel 11 to 87, then sends a=$CH10 and b=$CH11 to localhost:3000. The author notes that this OpenBeken mechanism reports data to the server, but does not parse responses from script level yet. [#20593560]

What is the difference between HTTP GET and POST when sending data to a server?

GET places data in the URL, while POST places data in the request body. The thread shows GET arguments after ?, such as mode=reply, t=3977701, and p=20578056. POST hides the content from the URL and uses a body with a Content-Type, such as application/json, plain text, or binary data. [#20593560]

How do I parse a JSON body from an HTTP POST request in Node.js using Express and body-parser?

Use bodyParser.json() middleware, then read values from req.body. The POST example imports express and body-parser, calls app.use(bodyParser.json()), and handles app.post('/', ...). It destructures { a, b } from the JSON body, checks isNaN, and returns { "sum": 100 } for 13 and 87. [#20593560]

How do I send a JSON POST request to a Node.js Express server with curl?

Use curl with -X POST, a JSON content header, and -d data. The demonstrated command sends Content-Type: application/json and a body containing "a": 13 and "b": 87 to http://localhost:3000/. Escaped quotation marks let JSON quotes stay inside the command string without ending it early. [#20593560]

Why does a browser XMLHttpRequest POST to localhost fail with a CORS error, and how do I fix it in Express?

It fails because the server response lacks an Access-Control-Allow-Origin header. The local HTML file has origin null, and the browser blocks the POST preflight request to localhost:3000. Fix it by installing cors, importing it, and adding app.use(cors()) before the JSON body parser. Restart the server after npm install cors. [#20593560]

What is CORS, and why does it block Ajax requests from a local HTML file to a Node.js server?

CORS blocks the Ajax request because the HTML file and server do not share an accepted origin. "CORS is a browser security mechanism that controls cross-origin HTTP access, requiring server headers such as Access-Control-Allow-Origin before JavaScript can read or complete restricted requests." In the thread, the browser reports origin null and blocks the POST to port 3000. [#20593560]

What is JSON, and how is it used as the body of an HTTP POST request?

JSON stores structured key-value data and can include nested objects and arrays. The thread shows a JSON object with name, email, age, and nested address fields. In the POST calculator, JSON carries { "a": 13, "b": 87 } in the request body while the header states Content-Type: application/json. [#20593560]

Express vs the built-in Node.js HTTP module — which is better for a small test server handling GET and POST requests?

Express is the better fit for this thread’s small GET and POST test server. The example uses Express routing with app.get and app.post, plus middleware for URL-encoded and JSON bodies. The built-in HTTP module is not demonstrated. The thread focuses on Express because it sets up parsing and callbacks with short code on port 3000. [#20593560]

How do I install missing Node.js packages like express or cors with npm when running server.js?

Install missing packages with npm in the script folder before restarting server.js. If Node reports no express package, run npm install express. If it reports Cannot find module 'cors', run npm install cors. The thread shows both installation steps after startup errors during the Express and CORS examples. [#20593560]

How can I send a JSON POST request from a simple HTML page using XMLHttpRequest?

Create an XMLHttpRequest, open a POST to http://localhost:3000/, set Content-Type to application/json, and send JSON.stringify. The example sends { a: 13, b: 87 }, waits for readyState === 4 and status === 200, parses xhr.responseText, and alerts the returned sum. CORS must be enabled on the server. [#20593560]

How do I use OpenBeken SendPOST to send JSON data such as voltage, current, or power measurements to a server?

Use SendPOST with the URL, port, content type, and JSON payload built from channel values. The thread demonstrates setting channel 10 to 13 and channel 11 to 87, then sending JSON containing a:$CH10 and b:$CH11 to localhost:3000. The same pattern can carry measurement values from a smart electrical outlet. [#20593560]

How can a Node.js test server be adapted later to log smart outlet measurements into InfluxDB or another database?

Replace the demo sum response with database-write logic after parsing GET or JSON POST data. The thread mentions InfluxDB specifically and points to its HTTP API as a later target. A practical path is to keep the Express receiver on port 3000, validate measurement fields, then forward voltage, current, power, or temperature records to the database endpoint. [#20593560]
AI summary based on the discussion. May contain errors.
ADVERTISEMENT