How can i get values of parameters using postman? - node.js

I am working on Node JS and PostgreSQL and I am creating REST web service using this. I have created a post method and calling web service through POSTMAN but unable to get parameter values in my function. Web service inserting null value in my PostgreSQL table. I am using Visual studio 2015 unable to debug code. How can I achieve this ?
queries.js
var promise = require('bluebird');
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://test:12345#localhost:8080/test';
var db = pgp(connectionString);
function getAllTask(req, res, next) {
debugger;
db.any('select * from tasklist')
.then(function (data) {
res.status(200)
.json({
status: 'success',
message: 'Retrieved ALL puppies',
data: data
});
})
.catch(function (err) {
return next(err);
});
}
function addTask(req, res, next) {
debugger;
//var task_name = req.param('task_name');
//var task_type = req.param('task_type');
var task_name = req.body.task_name;
var task_type = req.body.task_type;
console.log(req.body);
db.func('inserttask', [task_name, task_type])
.then(function () {
res.status(200)
.json({
status: 'success',
message: 'Inserted one task'
});
})
.catch(function (err) {
return next(err);
});
}
module.exports = {
getAllTask: getAllTask,
addTask: addTask
};
index.js
var express = require('express');
var router = express.Router();
var db = require('../queries');
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/api/tasklist', db.getAllTask);
router.post('/api/addtask', db.addTask);
module.exports = router;
server.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 index = 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', 'jade');
// uncomment after placing your favicon iblic
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
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 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 assuming that you are already using express js as framework for node js.
First of all you need to install body-parser module from npm:-
$ npm install body-parser --save
Once you have installed body-parser, add following code once after you have defined app variable:-
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // to support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support encoded bodies
Now you can access your post request body paramters as req.body.task_name and req.body.task_type
Hope it works and I am sorry if I have misunderstood your question.

You need to add Content-Type: application/json inside Headers when you send request through POSTMAN.

Related

Is it possible to see an image using postman?

I have created a Node.JS REST API server, and tried to test it by sending a GET request on https://localhost:3443/public/images/logo.png that logo.png image exist and I can see it in the directory. But the Postman gives me Not Found 404 error message.
This is my imagesRouter.js:
const express = require('express');
const bodyParser = require('body-parser');
const Images = require('../models/images');
var authenticate = require('../authenticate');
const imagesRouter = express.Router();
const cors = require('./cors');
imagesRouter.use(bodyParser.json());
imagesRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } );
imagesRouter.route('/')
//.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Images.find({})
.then((images) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(images);
}, (err) => next(err))
.catch((err) => next(err));
})
module.exports = imagesRouter;
And this is 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 usersRouter = require('./routes/usersRouter');
var imagesRouter = require('./routes/imagesRouter');
const uploadRouter = require('./routes/uploadRouter');
const Images = require('./models/images');
//const uploadRouter = require('./routes/uploadRouter');
//const favoriteRouter = require('./routes/favoriteRouter')
var config = require('./config');
const mongoose = require('mongoose');
//mongoose.set('useCreateIndex', true);
mongoose.Promise = require('bluebird');
var passport = require('passport');
var authenticate = require('./authenticate');
// Connection URL
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
//useMongoClient: true,
/* other options */
useNewUrlParser: true ,
useUnifiedTopology: true
});
connect.then((db) => {
console.log("Connected correctly to server");
}, (err) => { console.log(err); });
var app = express();
// Secure traffic only
app.all('*', (req, res, next) => {
if (req.secure) {
return next();
}
else {
res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
}
});
// 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(passport.initialize());
app.use('/', index);
app.use('/users', usersRouter);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public/images',imagesRouter);
app.use('/imageUpload',uploadRouter);
//app.use('/imageUpload',uploadRouter);
//app.use('/favorites',favoriteRouter);
// 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;
EDIT: This is my app files tree:
You'll need to specify the base of the static router to point to the public folder. You are currently "mounting" the public folder on the root route in the current code. You can change this line
app.use(express.static(path.join(__dirname, 'public')));
To:
app.use('/public', express.static(path.join(__dirname, 'public')));
Alternatively, you can call the endpoint from postman (or any other client) as: https://localhost:3443/images/logo.png

Error: Route.get() requires callback functions

After I added an app-api file and followed the instructions in the book: Simon Holmes Getting MEAN with Mongo, Express, Angular, and Node.
I restart the application and it shows error:
image
How to fix it?
file app.js:
var express = require('express');
var path = require('path');
var http = require('http');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('./app_api/models/db');
//require('./app_server/models/db');
var routes = require('./app_server/routes/index');
var routesApi = require('./app_api/routes/index');
var users = require('./app_server/routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app_server', '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('/', routes);
app.use('/users', users);
app.use('/api', routesApi);
// 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;
file index.js in app_api\routes
var express = require('express');
var router = express.Router();
var ctrlLocations = require('../controllers/locations');
var ctrlReviews = require('../controllers/reviews');
// locations
router.get('/locations', ctrlLocations.locationsListByDistance);
router.post('/locations', ctrlLocations.locationsCreate);
router.get('/locations/:locationid', ctrlLocations.locationsReadOne);
router.put('/locations/:locationid', ctrlLocations.locationsUpdateOne);
router.delete('/locations/:locationid', ctrlLocations.locationsDeleteOne);
// reviews
router.post('/locations/:locationid/reviews', ctrlReviews.reviewsCreate);
router.get('/locations/:locationid/reviews/:reviewid',
ctrlReviews.reviewsReadOne);
router.put('/locations/:locationid/reviews/:reviewid',
ctrlReviews.reviewsUpdateOne);
router.delete('/locations/:locationid/reviews/:reviewid',
ctrlReviews.reviewsDeleteOne);
module.exports = router;
file locations in app_api\controllers:
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.locationsCreate = function (req, res) {
sendJsonResponse(res, 200, {"status" : "success"});
};
file reviews.js in app_api\controllers
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');
var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.reviewsCreate = function (req, res) {
sendJsonResponse(res, 200, {"status" : "success"});
};
The stack trace tells you exactly where the problem is:
ap_api\routes\index.js:7
i.e. Line 7 of index.js, which is this:
router.get('/locations', ctrlLocations.locationsListByDistance);
The error says that the callback is undefined. Here the 'callback' is ctrlLocations.locationsListByDistance, which doesn't appear to be in your locations controller.

SyntaxError: Unexpected token )

I am using Cassandra + Node.js to create an app, but I am receiving an error for this code:
C:\Users\userx\node-cassandra\app.js:44
app.post('/',new);
^
SyntaxError: Unexpected token )
at Module._compile (module.js:545:28)
This is my code
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 helenus = require('helenus');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var pool = new helenus.ConnectionPool({
hosts : ['localhost:9160'],
keyspace : 'webinar',
cqlVersion : '3.0.0',
//user : 'test',
//password : 'test1233',
//timeout : 3000
//cqlVersion : '3.0.0' // specify this if you're using Cassandra 1.1 and want to use CQL 3
});
pool.connect(function(err){
if(err){
throw(err);
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('cassandra',pool);
// 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.get('/', routes.index);
app.post('/', new);
app.delete('/', delete);;
// 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;
});
index.js
exports.index = function(req, res, next){
req.app.get('cassandra').cql('SELECT * FROM users LIMIT 10',function(err, users){
if(err){
return next(err);
}
res.render('index', { title: 'Users', users: users });
});
};
exports.new = function(req, res, next){
var insert = 'UPDATE users SET first_name=?, last_name=? WHERE email=?',
params = [req.body.first_name, req.body.last_name, req.body.email];
req.app.get('cassandra').cql(insert, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
exports.delete = function(req, res, next){
var remove = 'DELETE FROM users WHERE email=?',
params = [req.body.email];
req.app.get('cassandra').cql(remove, params, function(err, users){
if(err){
return next(err);
}
res.redirect('/');
});
};
Error
SyntaxError: Unexpected token )
i just tried to change the app.post('/',routes.new);
but it showed inheritance mustnot be done
Please tell me where is my mistake
new is a reserved word in ECMAScript. I don't think you will be able to use it as a member name as it is being interpreted as creating a new object.

node express express.static prevents access from root path '/'

I am using express and I have a catch all route
router.use('*',function(){...});
and a root route
router.use('/', function(){...});
I have this route placed after the
app.use(express.static(path.join(__dirname, 'public')));
this causes my routes to not fire when placed below the previous line. however if I put my routes above it my catch all is also called on static asset requests. is there a way I can catch all requests except for the assets in my public folder including the route '/'? I don't want to resort to using regex and having to update it every time a directory is added to the public directory.
sorry for not being more details here are the relavant files
//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();
/* This is going to initialize the menubar for nwjs it is currently commented out as this is a non issue at this point
setTimeout(function () {
//initialize passport
var passport = require('./helpers/passport.js');
//setup routes
//setup window menu
console = window.console;
console.log(passport);
passport.init(app);
var gui = window.require('nw.gui');
var win = gui.Window.get();
var menu = new gui.Menu({
type: 'menubar'
});
menu.createMacBuiltin('jist', {
hideEdit: true,
hideWindow: true
});
gui.Window.get().menu = menu;
},1000);*/
// 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('/', 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;
//window.location.href="http://localhost:3000";
this is my index router
//routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.use('*', function(req, res, nex){
var path = req.originalPath;
if(~['/users/login', '/users/signup'].indexOf(path) || req.user) return next();
if(!req.user) return res.redirect('/users/login');
});
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;

http://localhost:3000/api/posts i am getting COULD NOT GET ANY RESPONSE. using POSTMAN

// this is app.js which is the main application 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 api = require('./routes/api');``
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/api', api);
// 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;
and this is api.js which implements the RESTful API.Post is a resource and because of this we will implement a /posts API which will First we'll implement placeholder route handlers for the /posts api within api.js.
var express = require('express');
var router = express.Router();
//api for all posts
router.route('/posts')
//create a new post
.post(function(req, res){
//TODO create a new post in the database
res.json({message:"TODO create a new post in the database"});
})
.get(function(req, res){
//TODO get all the posts in the database
res.json({message:"TODO get all the posts in the database"});
})
module.exports = router;
i am getting this on postman
You should be going to
http://localhost:3000/api/posts
Not
http://localhost:3000/routes/api/posts
..
Edit:
I didn't realize you're trying to call
req.send
Well that is not a method of
req (request)
You're looking for
res (response)
And on top of that you're trying to send a json result, not plain text so use
res.json
Instead of
res.send
I don't see you starting the server with app.listen(3000). You merely export the express app.
Or is there a different module that spins up the server?

Resources