From javascript on the client side I send 3 variables per ajax post, and on the server I try to view the json content of the client and it shows me undefined, I do not know where the problem is, I attach the code (refactored):
file : ./routes/index.js
'use strict'
const express = require('express')
const user_controller = require('../controller/user')
const api = express.Router()
// pagina de Inicio
api.get('/index',function(req,res){
res.render('index')
})
// Gestion de usuarios
api.get('/usuarios',user_controller.getAllUsers)
api.post('/usuarios',user_controller.newUser)
api.get('/usuario',user_controller.getUser)
api.post('/logear',user_controller.logear)
api.post('/registrar',user_controller.registrar)
module.exports = api
file : ./controller/user.js
function registrar(req,res){
var bcrypt = require('bcrypt');
var BCRYPT_SALT_ROUNDS = 12;
var user = req.body.user;
var email = req.body.email;
var pass = req.body.pass;
console.log('info: ' + user + ' ' + email + ' ' +pass);
//console.log('perro: ' + req.body);
// encriptamos la contraseƱa
bcrypt.genSalt(10, function(err, salt) {
if(error) throw error;
else{
bcrypt.hash(pass, BCRYPT_SALT_ROUNDS, function(err, hash) {
pass = hash;
});
}
});
//bcrypt.hash(pass, BCRYPT_SALT_ROUNDS).then(function(hashedPassword) {pass = hashedPassword});
conexion_db.query({ ... etc
file: ./app.js
'use strict'
//configuracion del servidor
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.set('view engine','jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
const api = require('./routes');
app.use('/api',api);
module.exports = app
file: client.js
$.ajax({
url: 'http://localhost:3000/api/registrar',
data: JSON.stringify({'user': $('#nick').val(),'email': $('#email').val(),'pass': $('#pass').val()}),
type: "POST",
dataType: 'json',
success: function(json) {
console.log("json: " + json.estado);
console.log("json: " + json.user);
console.log("json: " + json.pass);
I get on cmd server, this: info: undefined undefined undefined
The bodyParser middleware can not handle the json data because you have not set the ContentType.jQuery ajax default value of contentType parameter is "application/x-www-form-urlencoded; charset=UTF-8".But you are sending data in json type.You need to set ContentType to application/json.
You can also give PlainObject to the data parameter.
Related
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.listen(3000,function(){
console.log("server is running");
})
app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.post("/",function(req,res){
var url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?";
var pincode = req.body.pinCode;
url = url + "pincode=" + pincode;
var date = req.body.date;
url = url + "&date=" + date;
console.log(pincode,date);
request(url,function(err,res1,body){
res.send(body.centers);
})
})
for the above code (undefined) value is send in res.send(body.centers)
body is in json format given as below:
{"centers":[{"center_id":596215,"name":"MISSION UHC","address":"MISSION NADIAD","state_name":"Gujarat","district_name":"Kheda","block_name":"Nadiad","pincode":387002,"lat":22,"long":72,"from":"09:00:00","to":"18:00:00","fee_type":"Free"}
Try to see how body looks
request(url,function(err,res1,body) {
console.log(body);
})
If body output in terminal with double quote like :
{
"key": "value"
}
that's mean body is JSON string and you need to parsing it to object with :
body = JSON.parse(body)
Then send it :
res.send(body.centers)
When ran, I get an error saying:
undefined:1
[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
the code:
const express = require("express");
const app = express();
const https = require("https");
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.get("/",function (req,res) {
res.sendFile(__dirname + "/public/index.html")
app.use(express.static('public'));
})
app.post("/",function(req,res){
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const data = {
members:{
email_address: email,
status:"subscribed",
merge_fields:{
FNAME:firstName,
LNAME:lastName
}
}
}
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/";
const options = {
method:"POST",
auth:"sudolake:api_key"
}
const request = https.request(url, options, function(response){
response.on("data",function(){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
})
app.listen(3000, function(){
console.log("the server is up & running");
})
I know its probably something with the "const jsonData = JSON.stringify(data);" but I don't know what, its probably really stupid, thanks for any help
The following doesnt seem to work. It's simple Express sample code. You can ignore the other responses. Im just trying to get the basic '/' home page working and that's refusing to work. Code is as follows:
var express = require('express');
var sR = require('./routes/index');
var path = require('path');
var urlencoded = require('url');
var bodyParser = require('body-parser');
var json = require('json');
var methodOverride = require('method-override');
var jade = require('jade');
var fs = require('fs');
var http = require('http2');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbLoc = 'mongodb://localhost:27017';
const dbName = 'gothamDB';
var dbConn = null;
const dbURL = "mongodb://gotthamUser:abcd1234#localhost:27017/gothamDB"
const mongoClient = new MongoClient(dbURL, { useNewUrlParser: true, useUnifiedTopology: true});
// Use connect method to connect to the server
dbConn = mongoClient.connect(function(err, client) {
assert.strictEqual(null, err);
console.log("Connected successfully to server");
dbConn = client;
});
var app = express();
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', jade);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
app.post('/create_collection', function(req, res){
var db = dbConn.db('gothamDB');
var userData = db.createCollection(req.body.coll_name, function(err){
if(err){
res.send('Error creating database: ' + req.body.coll_name);
return;
}
res.send('Database ' + req.body.dbname + ' created successfully');
});
});
app.post('/new_contact', function(req, res){
var name = req.body.name;
var phone = req.body.phone;
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
collection.insert(
{name : name, phone: phone}
, function(err, result) {
assert.strictEqual(err, null);
assert.strictEqual(1, result.result.n);
assert.strictEqual(1, result.ops.length);
res.send("Inserted new record into the collection");
});
});
app.post('view_contact', function(req, res){
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
coll.find({'phone' : req.body.phone}).toArray(function(err, docs){
if(err) {
res.send("Error looking up the data");
return;
}
res.send(docs);
return;
});
});
app.post('delete_contact', function(req, res){
var db = dbConn.db('gothamDB');
var coll = db.collection(req.body.coll_name);
coll.deleteOne({'phone' : req.body.phone}).toArray(function(err, docs){
if(err) {
res.send("Error looking up the data");
return;
}
res.send(docs);
return;
});
});
//const key = path.join(__dirname + '/security/server.key');
//const cert = path.join(__dirname + '/security/server.crt');
const options = {
key: fs.readFileSync(__dirname + '/security/server.key'),
cert: fs.readFileSync(__dirname + '/security/server.crt')
}
http.createServer(app).listen(app.get('port'), function(err){
console.log('Express server lisetning on port ' + app.get('port'));
})
console.log("Server started");
Any clue? Browser shows as follows:
Itt's showing an ERR_INVALID_HTTP_RESPONSE
if I run a curl command, it shows the following:
NodeExample % curl -X GET 'http://localhost:8080/'
Warning: Binary output can mess up your terminal. Use "--output -" to tell
Warning: curl to output it to your terminal anyway, or consider "--output
Warning: <FILE>" to save to a file
If I put a breakpoint at the line:
res.send("Hello World");
that never hits. I've also tried putting in
res.header("Content-Type", "application/json");
but since the breakpoint never hits, it is not going to help I guess.
You are using set here
app.set('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
It should be get
app.get('/', function(req, res){
res.send("Hello World");
res.end();
console.log("Hello World sent");
});
when i submit the register form ,the data from that register page should be posted on the console.. and I try to print that result using "req.body.Username" , it says undefined and when i view the req in console. The body seems to be an empty set like " {} ", how to post my form details in body to view in console and how to get rid of that "undefined" error?
app.js
const express = require('express');
const flash = require('connect-flash');
const path = require('path');
const request = require('request')
const expressValidator = require('express-validator');
const authRoutes = require('./routes/auth-routes');
const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const db = require('./config/db');
const registerc = require('./registerc');
const loginc = require('./loginc');
const registerRoute = require('./routes/register');
const fs = require('fs');
// const request = require('./modules/module1')
const app = express();
// set view engine
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// set up routes
app.use('/auth', authRoutes);
app.use('', registerRoute);
// create home route
app.get('/', (req, res) => {
res.render('home');
res.render('mycourses', {
final1: final1
});
res.render('recent', {
final2: final2
});
});
// fetching course details
request(options, function (error, response, result) {
if (error) throw new Error(error);
// console.log(result);
// final1 = JSON.stringify(result)
final1 = JSON.parse(result);
// console.log(final1);
});
// fetching User recent Activity
request(options, function (error, response, result) {
if (error) throw new Error(error);
// console.log(result);
final2 = JSON.parse(result);
// console.log(final2);
// console.log(final2.length)
});
app.use(session(
{
secret : 'secret',
saveUninitialised : true,
resave : true
}
));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(flash());
// app.use(function(res,req,next){
// res.locals.success_msg = req.flash('success_msg');
// res.locals.error_msg = req.flash('error_msg');
// res.locals.error = req.flash('error');
// next();
// })
// app.post('/api/register',registerc.register);
// app.post('/api/login', loginc.login);
app.listen(3000, () => {
console.log('app now listening for requests on port 3000');
});
In your app.js, update the register auth from
app.use('', registerRoute);
To
app.use('/soemRoute', registerRoute);
I am using formdata to have multipart data and for that i am using busboy-body-parser. But somehow the body is not accessible and the value is undefined.
app.js
var express = require('express');
var mongoose = require('mongoose');
var Uploader = require('s3-image-uploader');
var config = require('./config.js');
var busboyBodyParser = require('busboy-body-parser');
var uploader = new Uploader({
aws: {
key: config.awsKey,
secret: config.awsSecret
},
websockets: false
});
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var multer = require('multer');
// var uuid = require("uuid");
var app = express();
var morgan = require('morgan');
var path = require('path');
var port = process.env.PORT || 3000;
var foodtrucklist = require('./controller/foodtrucklist.js');
var login = require('./controller/login.js');
var itemInfo = require('./controller/item_info.js');
var review = require('./controller/reviews.js');
var popularitems = require('./controller/popularitems.js');
var foodtruck = require('./model/datafoodtruck');
var truckData = require('./model/foodtruck.js');
var webToken = require('./controller/webtoken.js');
var userprofile = require('./controller/userprofile.js');
var notificationdata = require('./model/dataNotifications.js');
var notification = require('./controller/notifications.js');
var foodtruckItemList = require('./controller/item_list_foodtruck.js');
var orderList = require('./controller/orders_foodtruck.js');
var ordermanagement = require('./controller/ordermanagement.js');
var db = mongoose.connect(config.local_mongo_url);
mongoose.connection.once('connected', function() {
console.log("Connected to database")
// foodtruck.save();
// notificationdata.save();
});
app.use(bodyParser.urlencoded({
extended: true
}));
// app.use(multipartyMiddleware);
app.post('/testupload', function(req, res) {
// var file = req.files.file;
// var stream = fs.creatReadStream(req.files.file.path);
// return s3fsImpl.writeFile(file.originalFilename, stream).then(function() {
// console.log(file);
// return;
// fs.unlink(file.path, function(err) {
// if (err) console.error(err);
// res.json({
// status: '200',
// message: 'uploaded'
// });
// });
// })
res.connection.setTimeout(0);
uploader.upload({
fileId: 'someUniqueIdentifier',
bucket: 'quflip',
source: './public/images/food-3-mdpi.png',
name: 'food-3-mdpi.png'
},
function(data) { // success
// console.log('upload success:', data);
res.json({
status: '200',
message: 'image uploaded successfully'
});
},
function(errMsg, errObject) { //error
// console.error('unable to upload: ' + errMsg + ':', errObject);
res.json({
status: '404',
message: 'image is not uploaded successfully'
});
});
});
// app.use('/public/images', express.static(__dirname + '/public/images'));
app.use(morgan('dev'));
// app.use(bodyParser.urlencoded({extended: true}));
app.get('/foodtrucklist', foodtrucklist);
app.post('/itemInfo', itemInfo.itemInfo);
app.post('/likeitem', itemInfo.likeItem);
app.get('/popularitems', popularitems);
app.post('/notification', notification);
app.post('/submitreview', review.addreview);
app.post('/getreview', review.getReview);
app.post('/addOrder', ordermanagement.addOrder);
app.post('/orderHistory', ordermanagement.orderHistory);
app.post('/cancelOrder', ordermanagement.cancelOrder);
app.post('/getOrderStatus', ordermanagement.getOrderStatus);
app.post('/rateOrder', ordermanagement.rateOrder);
app.post('/updateUser', userprofile.updateUser);
app.post('/getUserInfo', userprofile.getUserInfo);
app.post('/createToken', webToken.createToken);
app.post('/checkToken', webToken.checkToken);
app.post('/itemList', foodtruckItemList.getItemList);
app.post('/updateItemStatus', foodtruckItemList.updateItemStatus);
app.post('/addItem', foodtruckItemList.addItem);
app.post('/deletItem', foodtruckItemList.deletItem);
app.post('/orderlist', orderList.getOrderList);
app.post('/statusOrderlist', orderList.getStatusOrderList);
app.post('/updateorder', orderList.updateOrder);
app.use(bodyParser.urlencoded({extended: false}));
app.use(busboyBodyParser({ limit: '50mb' }));
app.post('/login', function(req,res) {
console.log("body" + req.body.email_id + "file" + req.files);
});
app.listen(port, function() {
console.log('express listining on port' + port);
});
so, how can I access body parameters even I tried to use multer but the problem was same.
Busboy has parameters inside busboy.on('field') event
We explicitly have to attach it to req.body before Busboy.on('finish') event like so :
busboy.on('field', (fieldName, value) => {
req.body[fieldName] = value
})
This will attach parameters to req.body as it should be !