I'm developing a site in node.js and I'm trying to separate frontend and backend. To do so I'm using http.request to send/ask to the backend data but I can't pass data in the body. I put the code below to clarify the problem.
/**
* FRONTEND
* POST /
* Login (Home)
*/
router.post('/home', async (req, res) => {
try {
const { mail, password } = req.body;
var datas = querystring.stringify({
"mail": mail,
"password": password
});
var options = {
host: 'localhost',
port: 3000,
path: '/login',
method: 'POST'
};
var data;
var request = http.request(options, function(r) {
r.setEncoding('utf8');
if(r.statusCode === 200){
var bodyChunks = [];
r.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
data = bodyChunks; //Buffer.concat(bodyChunks);
res.cookie('token', data, { httpOnly: true });
res.redirect('/');
});
} else {
console.log('Not working, code: '+r.statusCode);
}
});
request.write(datas);
request.end();
request.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
} catch (error) {
console.log(error);
res.status(401).json({message:'Invalid credentials'});
}
});
/**
* BACKEND
* Check Login
*/
const authMiddleware = (req, res, next) => {
const token = req.body.token;
console.log(token); //it prints 'undefined'
if(!token) {
return res.status(401).send('Unauthorized access');
}
try {
const decoded = jwt.verify(token, jwtSecret);
req.userId = decoded.userId;
next();
} catch (error) {
res.status(401).send('Unauthorized access');
}
}
/**
* BACKEND
* GET /
* Dispense
*/
router.get('', authMiddleware, async (req, res) => {
try {
const data = await Dispensa.find();
res.send(data).status(200);
} catch (error) {
console.log(error);
}
});
As I said before I tried to pass data in the http request body but in the backend I don't receive anything.
EDIT To simplify I'm trying with this test but still don't work.
//index.js
//...
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//...
app.post(function (req, res) {
res.json(req.body)
});
//BACKEND - Test
router.post('', async (req, res) => {
try {
console.log(req.body.token);
res.send("TEST").status(200);
} catch (error) {
console.log(error);
}
});
//FRONTEND - Test
router.get('', async (req, res) => {
try {
var request = http.request(options, function(res) {
if(res.statusCode === 200){
var bodyChunks = [];
var data;
res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
data = Buffer.concat(bodyChunks);
console.log(data);
});
}
});
// request.write(body);
request.end("token=ABCDEFGH");
request.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
} catch (error) {
console.log(error);
}
});
I think you are looking for BodyParser, req.body is available after the middleware
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());