Asaf Fisher Asaf Fisher - 3 years ago 63
Javascript Question

NodeJS res.body is undefined only on one router

I am sending data using swift to a nodeJS server.
Here is the Swift Code:

var data:[String:String] = [:]
data["ABC"] = "nothing"
let req = HTTPRequest(url_to_request: "https://xxx.xxx.xx.x/update", method: HTTPRequest.HTTPRequestMethod.post, data: Profile.toJSON(dict: data))


Here is the NodeJS:

console.log("Server is up!");
var bodyParser = require('body-parser');
var express = require('express');
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var http = require('http');
var https = require('https');
var fs = require('fs');
var bcrypt = require('bcryptjs');
var sslOptions = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('cert.pem', 'utf8'),
passphrase: 'phrase',
rejectUnauthorized: false
};


var app = express();


//Variables:

var httpPort = 8888;
var httpsPort = 8443;



app.use(bodyParser.urlencoded({
extended: false,
limit: '20mb'
}));

app.use(bodyParser.json({
limit: '50mb'
}));

// parse application/json json size limit

// parse application/x-www-form-urlencoded




// setup server
app.set("port_https", httpsPort);

//check secure connection

app.all("*", function(req, res, next) {
console.log("Secure connection: " + req.secure);
if (req.secure) {
return next();
}
res.redirect("https://" + req.hostname + ":" + app.get("port_https") + req.url);
});








// add User

app.post('/register', register);
//signIn
app.post('/login', logIn);

//Update user's profile details.

app.post('/update', updateProfile);

// Request profile details.
app.post('/profile', profileRequest);


function updateProfile(req, res) {
console.log(res.body); // ---> undefined
}


When I send a post request with data to login, profile, register routers res.body is working well. But when I send data to update for some reason req.body is undefined:

ERROR:

Server: Secure connection: true

Server: undefined #----> log of res.body

Server: Connected successfully to databse!

stderr: /home/asaf/NodeJS/IBQA/IBQA_Server/node_modules/mongodb/lib/mongo_client.js:350
throw err
^

TypeError: Cannot read property 'ABC' of undefined
at /*****/server.js:92:33
at connectCallback (*****/mongo_client.js:428:5)
at /*****/node_modules/mongodb/lib/mongo_client.js:347:11
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)

closing code: 1

Answer Source

Your request if there in the req variable, res is used to send the response. Try console.log(req.body)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download