This example uses the fetch function of Javascript to issue an HTTP POST request to an Express server. The request includes a JSON message which the server stores and returns to the client. Subsequent HTTP GET requests can retrieve the stored message.
git clone https://github.com/portsoc/tinypostupload.git
cd tinypostupload
npm install
npm startThen open http://localhost:8080 in your preferred browser.
The example comprises two parts, a server and a client.
- listens on port 8080 for HTTP requests.
- will serve any files contained in the client folder (therefore requesting
http://localhost:8080/will return theindex.htmlfile). - provides a special path
http://localhost:8080/messagewith different behaviours for 'POST' and 'GET' requests.- When a
GETrequest is received, stored message is returned. - When a
POSTrequest is received, the server updates the message that the server sends in response to aGETrequest. This updated message is returned to the client as a response to the POST request (so the client can clearly check if the update was successful).
- When a
You can test to see what the current message is by opening http://localhost:8080/message in your preferred browser.
- The client uses a function called
sendMessageto undertake the round-trip from client, to server, and back to the client. ThissendMessagefunction:- runs whenever the
uploadbutton is pressed. - constructs an object that describes the method to be used (
POST), a header block where the data format of JSON is specified, and abodythat contains the stringified JSON message that is sent to the server. - waits for the server to respond and updates the page to reflect what the server sent back (which should be exactly what was sent).
- runs whenever the