I'm creating a simple client-server program using Node and Express. The program should be able to accept a JSON input on the client-side, perform some logic, and then pass information to the server-side.
Currently I can successfully give input to the client, however, the server-side simply returns {} when outputting request.body to the console after performing a POST from the client-side.
client.js:
const clientPort = 9300;
const serverPort = 9400;
var express = require('express');
var http = require('http');
var app = express();
app.use(express.json());
// json callback
app.post('/api', function(request, response) {
console.log(`api callback`);
// log the received json
var input = request.body;
console.log(`Received JSON: ${JSON.stringify(input)}`);
var options = {
host: 'localhost',
port: serverPort,
path: '/',
method: 'POST',
header: {
'Content-Type': 'application/json'
}
};
const httpReq = http.request(options, function(response) {
response.setEncoding('utf8');
response.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
response.on('end', () => {
console.log('No more data in response.');
});
});
// write word to request
httpReq.write(JSON.stringify(input));
httpReq.end();
});
// listen on port 9300 for inputs
app.listen(clientPort, 'localhost', () => {
console.log(`Client listening on port ${clientPort}...`);
});
server.js:
const serverPort = 9400;
var express = require('express');
var app = express();
app.use(express.json());
// expect to receive the JSON input
app.post('/', function(request, response) {
console.log(`server callback`);
console.log(JSON.stringify(request.body));
});
// listen on port 9400 for inputs from client
app.listen(serverPort, 'localhost', () => {
console.log(`Server listening on port ${serverPort}...`);
});
Example input:
curl --header "Content-Type: application/json" \ INT ✘ 11s
--request POST \
--data '{"word":"test"}' \
http://localhost:9300/api
client.js output (based on above input):
Client listening on port 9300...
api callback
Received JSON: {"word":"test"}
Finally, the server.js output:
Server listening on port 9400...
server callback
{}
CodePudding user response:
You must use the express urlencoded middleware so that it can interpret the body object in your request.
Underneath app.use(express.json());
put the following line
app.use(express.urlencoded({ extended: true }));
More information here: https://www.geeksforgeeks.org/express-js-express-urlencoded-function/
CodePudding user response:
All I had to do was replace header in var options with headers.
I'm going to go slap myself in the face.
