Reputation: 8609
I am writing some code that allows me to send messages back and forth from two node instances using HTTP & Express.
Each client generates a UUID type of identification and then sends it to the main server for storage and authentication.
Here is the client, you can see at the bottom that it generates what i beleive to be a json string, i assign a variable before that contains an ID, i am trying to use this ID to send to the server for proccessing.
Client.js
var request = require('request');
var sendservlet = request.post;
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
if (fs.existsSync('foo.txt')) {
console.log('Found ');
fs.readFile('foo.txt', "utf-8" , function (err, data) {
if (err) throw err;
console.log(data);
});
} else {
console.log("Did not find file, i must first register you to the server.");
function randomValueHex (len) {
return crypto.randomBytes(Math.ceil(len/2))
.toString('hex')
.slice(0,len);
}
var ID = randomValueHex(7)
console.log("Your New Identification Number Is: " + ID);
sendservlet(
'http://192.168.1.225:3000',
{ form: { key: ID } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
console.log(ID)
}
}
);
}
Server.JS
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
var crypto = require('crypto');
app.post('/', function (req, res) {
res.send('POST request to the homepage');
console.log(req.body.form.key);
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
The server cannot seem to be able to read it, i believe that i cannot call the variable like that.
To help narrow this issue down, I am strictly asking why the ID variable cannot be transmitted in
sendservlet(
'http://192.168.1.225:3000',
{ form: { key: ID } },
thank you very much for any advice available!
Upvotes: 3
Views: 1385
Reputation: 70163
Instead of console.log(req.body.form.key);
, you just want console.log(req.body.key);
The form
key is just what request
uses for (basically) "This is my form data, so this is the stuff to POST to the URL." Whatever was in form
on the request
side just gets put into req.body
on the express
side. So you want req.body.key
.
Upvotes: 2