I have this node js program which should return asked variable in the console but it is returning undefined here is code and the input i have trying to parse :-
router.post('/createorder',function(req,res){
console.log(req.body.ProductName);
// var obj=JSON.parse(req.body);
res.send(req.body);
});
the input :
{
"ProductName":"Wine",
"ProductPrice":"500",
"ProductQuantity":"2",
"ProductCost":"1000",
"SellerId":"2"
}
and here is the main module i'm using
var express= require('express');
var routes=require('./routes/api');
var bodyparser=require('body-parser');
var mysql = require('mysql');
var db=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'nodemysql'
})
//setting up express
var app = express();
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
app.use(routes);
//listen for requests
/*app.get('/',function(req,res){
console.log('get trial method called');
res.send({name:'Atul'});
});*/
app.listen(3000,function(){
console.log('server started on port 3000 ');
});
i want to acess an specific object in order to store in the database?
As soueuls mentioned in the comments, you need to make sure express can parse the body of the request as it doesn't do this by default. Assuming you are using express framework. You could have something like this.
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
Now you can read the body.
notice if you console log your req object before you add in the code above, you will not see the body property.
UPDATE
this is what i have in my app.js file
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
In my routes/index.js i have the following
var express = require('express');
var router = express.Router();
router.post('/createorder',function(req,res){
console.log(req.body);
// var obj=JSON.parse(req.body);
res.send(req.body);
});
module.exports = router;
i tested this with postman app and it works.
Related
So I am using Express File Upload and when I attempt to send a post request to it, it returns the error from the error-handler that is set up, which essentially it couldn't find any files when I console.log(req.files) it returns undefined, which is why the error is being sent back, but I don't know how to fix the problem.
Index.js
router.post('/upload-avatar', async (req, res) => {
try {
console.log(req.files)
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});
} else {
//Use the name of the input field (i.e. "avatar") to retrieve the uploaded file
let avatar = req.files.avatar;
//Use the mv() method to place the file in upload directory (i.e. "uploads")
avatar.mv('./uploads/' + avatar.name);
//send response
res.send({
status: true,
message: 'File is uploaded',
data: {
name: avatar.name,
mimetype: avatar.mimetype,
size: avatar.size
}
});
}
} catch (err) {
res.status(500).send(err);
}
});
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const _ = require('lodash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use(fileUpload({
createParentPath: true
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I am using an azure server, and at the moment I am using postman to get it working first!
Thanks In Advance!
Middlewares should be ordered appropriately. Your file upload middleware was placed below your index router. So when a request hits the server Express would run your indexRouter’s handler before the upload middleware and unless your handler calls next(), the file upload middleware would not process your request. And you cannot call next() since it would mean “I’m done with my part, hand this request (req) to the next middleware/handler”.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fileUpload = require('express-fileupload');
const cors = require('cors');
const bodyParser = require('body-parser');
const _ = require('lodash');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileUpload({
createParentPath: true
}));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
my database in mongoDb is connected to my nodeJS i can read it there my nodeJs api is connected to my client-side (in reactJS) and i can send data from my nodeJs api using express-generator to my client-side and is working but when i tried to send my mongoDb database to the client-side is not working( but i'm still getting status 200 but my array is not here . I can't figure out why? i cant see the db when i call the api in postman so i assume the error is in the server-side . If i had a consol.log i can see the db but when i use return it is not working and i cant see the data in postman
here my nodeJs code:
var mongodb = require('mongodb')
var MongoClient = mongodb.MongoClient
var connectionURL = 'mongodb://127.0.0.1:27017'
var databaseName = 'projet_Ecommerce';
const dataFromDb = () => {
MongoClient.connect(connectionURL, {
useNewUrlParser: true
}, (error, client) => {
if (error) {
return console.log('Unable to connect to database')
}
console.log('Connected correctly !');
var db = client.db(databaseName)
db.collection('product').find().toArray(function(error, data) {
if (error) {
return console.log('Unable to find the user')
}
return (data);
})
// Pointer - go to doc
// db.collection('tasks').find({completed: false}).toArray()
})
};
module.exports = dataFromDb
routres / index.js:
var express = require('express');
var router = express.Router();
const bodyParser = require('body-parser')
var dataC = require('../public/javascripts/dataFromDb')
// data = JSON.stringify(data);
// console.log(dataFromDb())
/* GET home page. */
router.get('/', function(req, res, next) {
//console.log(dataFromDb())
res.send(dataC())
});
//console.log(dataFromDb())
module.exports = router;
app.js:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require("cors")
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
var bodyParser = require("body-parser")
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
other files no change
I am using body-parser but it's not working and I don't know what the problem is.
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const bodyParser = require('body-parser');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', redirection, function(req, res, next) {
res.redirect('index', {title: 'Home'});
});
router.get('/country', function(req, res, next) {
// CountryName
res.render('country',
{
title: 'Home',
mainJS: 'main.js',
//country: req.body.countries
});
console.log(req.body)
});
function redirection(req, res){
if (req.url == '/'){
res.redirect('/country');
}
}
module.exports = router;
In this code it throws {}
What is the problem?
Your server only receives a request body in POST (or PUT or PATCH) operations, not in GET operations. You don't have router.post() in your sample code, so it seems you are not handling POSTs. Therefore, no req.body.
You can find your https://example.com/?query=parameters&query2=parameters at req.params.query and req.params.query2.
You can't use the location bar of a browser to do a POST: they from a form posts or xhr / fetch operations.
I'm learning about REST with node.
I'm trying to use post to add an element to my db.
My code:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var AdModule = require('../models/ad');
router.route('/')
.get((req, res) => {
AdModule.find((err, col) => {
if (err)
res.send(err);
res.json(col);
})
})
.post((req, res) => {
var ad = new AdModule();
ad.title = req.body.title;
ad.desc = req.body.desc;
ad.price = req.body.price;
ad.save(err => {
if (err)
res.send('err' + err);
res.json({msg: 'Created'});
})
res.json(req);
});
module.exports = router;
When using post I get req.body is undefined.
My server.js code:
'use strict';
//======================= Base setup =======================\\
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('./globals/config');
var index = require('./routes/index');
var users = require('./routes/users');
var ads = require('./routes/ads');
var app = express();
//========================= DB =============================\\
mongoose.connect(config.db, () => {
console.log('Connected');
});
//========================= Routes =========================\\
app.use('/', index);
app.use('/users', users);
app.use('/ads', ads);
//========================= Parsers ========================\\
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// app.engine('html', require('ejs').renderFile);
// app.set('view engine', 'html');
//========================= 404 ============================\\
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
//
// // error handler
// app.use(function(err, req, res, next) {
// // set locals, only providing error in development
// res.locals.message = err.message;
// res.locals.error = req.app.get('env') === 'development' ? err : {};
//
// // render the error page
// res.status(err.status || 500);
// res.render('error');
// });
//
//==========================================================\\
module.exports = app;
So I am using body parser.
This is how I'm posting with postman:
What can be the reason for this madness?
I'm guessing it's something with server.js but have no idea what.
I was following this tutorial.
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4#creating-routes-for-a-single-item
Express middlewares executed by order that they are defined, in your case bodyParser defined after ads middleware, just move asd to the bottom
Put your parsers above your routes -- as it happens now, requests are hitting the routes before they have a chance to go through the parsers.
I'm new to nodejs, below is my app.js I installed by express --sessions --css less --hogan app command.
I tried to separate the commented line in app.js move to a new file call route_handler.js.
I'm not sure am I doing correct I only add a require('./route_handler.js'); in app.js and should I have to export in route_handler.js but it is express() ?
How to solve it?
Does require means already execute the code in the file?
app.js
var express = require('express');
var path = require('path');
// var favicon = require('serve-favicon');
// var logger = require('morgan');
// var cookieParser = require('cookie-parser');
// var bodyParser = require('body-parser');
// var routes = require('./routes/index');
// var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
// end: view engine setup
require('./route_handler.js');
// // uncomment after placing your favicon in /public
// //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
// app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(require('less-middleware')(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', routes);
// app.use('/users', users);
// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// // error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
route_handler.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// var app = express();
var routes = require('./routes/index');
var users = require('./routes/users');
// uncomment after placing your favicon in /public
//express().use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
express().use(logger('dev'));
express().use(bodyParser.json());
express().use(bodyParser.urlencoded({ extended: false }));
express().use(cookieParser());
express().use(require('less-middleware')(path.join(__dirname, 'public')));
express().use(express.static(path.join(__dirname, 'public')));
express().use('/', routes);
express().use('/users', users);
// catch 404 and forward to error handler
express().use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// expore express() ??
Your problem is that the route_handler.js script creates new express instances in every use call, and non of them are connected to the app created in your app.js.
What you should probably do is something like:
route_handler.js
// !!!NOTE: no express = require !!!
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
function setupRoutes(app)
{
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
...
}
module.exports = setupRoutes;
and app.js
...
require('./route_handler.js')(app);
...