Is it possible to see an image using postman? - node.js

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

Related

How to call smart contract from nodejs app with web3

I have created a complete NODEJS app with routes and MySQL database and it listens on localhost:3000. And I have written a smart contract and tested it on remix online IDE.
smart contract:
pragma solidity ^0.4.11;
contract Hello {
string name;
function getName() constant returns(string){
return name;
}
function setName(string n) {
name = n;
}
}
My app.js:
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let logger = require('morgan');
let passport = require('passport');
let md5 = require('md5');
let LocalStrategy = require("passport-local");
let methodOverride = require("method-override");
let app = express();
let connection = require('./database');
let indexRouter = require('./routes/index');
let adminRouter = require('./routes/admin');
let studentRouter = require('./routes/student');
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride("_method"));
app.use(function(req, res, next) {
//make available inside our template
res.locals.currentUser = req.user;
//important: move to the code that handles the route
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// 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('/student', studentRouter);
app.use('/admin', adminRouter);
// 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 admin.js
var express = require('express');
var router = express.Router();
let connection = require('../database');
let md5 = require('md5');
// gets admin page
router.get('/', function(req, res, next) {
console.log("----------------------------IN ADMIN ROUTER");
let queryString = "SELECT * FROM `semester` WHERE status =1 ;";
connection.query(queryString, function (err, result) {
if (err) {
res.render('admin/admin', {title: 'admin', bool: 0, data: " "});
}
if(result){
res.render('admin/admin', { title: 'admin', bool: 1 , data: result });
}
else{
res.render('admin/admin', { title: 'admin', bool :0 , data: " " });
}
});
});
router.get('/profile', function(req, res, next) {
res.render('admin/profile', { title: 'Profile' });
});
router.get('/viewStudentRecord', function(req, res, next) {
res.render('admin/viewStudentRecord', { title: 'View student record', bool: 0, data: " " });
});
Now I want to call smart contract in admin.js
I have seen examples of using smart contracts from nodejs but that whole app is only dedicated to smart contract and they are single page app.
ps. I have installed GANACHE, METAMASK, WEB3

Error 404 not found error

In my index.ejs, there is a link which links to /signup:
Sign Up Here
This is my 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 indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//connect to mysql
var mysql = require('mysql');
var bodyParser = require('body-parser');
var connection = mysql.createConnection({
host:'localhost',
user: 'root',
password: '',
database: 'test'
});
connection.connect();
global.db = connection;
// all environments
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// 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));
});
// 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');
});
app.get('/',indexRouter); //call to index site
app.get('/login', indexRouter); // call to login site
app.get('/signup', usersRouter);
module.exports = app;
this is my users.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
message = '';
if(req.method == "POST"){
//post data
} else {
res.render('signup.ejs');
}
});
module.exports = router;
In my index page there is a link which link which directs user to a signup page. When I click on the link which is supposed to direct me to "http://localhost:3000/signup", it shows Error 404 Not found error. I am new to NodeJs. Any help is much appreciated. Thank you.
Changed the link in index.ejs to
Sign Up Here
Added this handler to users.js
router.get('/signup',function(req,res,next){
message = '';
if(req.method == "POST"){
//post data
} else {
res.render('signup');
}
});

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.

How can i get values of parameters using postman?

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.

How to share Session across multiple route JS files in ExpressJS

First of all, I am using:
express-session#1.14.2
express#4.14.0
I am basically trying to get a login system working and when user logs in, I set session.isloggedin = true.
So this is my 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 session = require('express-session');
var index = require('./routes/index');
var portfolioRoute = require('./routes/portfolio');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// 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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true,
maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));
app.use('/', index);
app.use('/portfolio', portfolioRoute);
// 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;
The index.html contains the login form.
Next, my index.js
var express = require('express');
var router = express.Router();
var util = require('util');
var api = require('../server/api.js');
var port = require('../server/portfolio.js');
var sess;
/* GET home page. */
router.get('/', function (req, res) {
sess = req.session;
console.log("SESSION IS: " + sess.isLoggedIn);
if(sess.isLoggedIn) {
res.render('portfolio', { isLoggedIn: true })
} else {
res.render('index', { isLoggedIn: false })
}
})
//END ------------
if(global.GLB_PORTFOLIO === null) {
port.getPortfolio(null, function(err, result) {
global.GLB_PORTFOLIO = result;
});
}
// API Routes
//router.use('/api', router);
router.route('/api/login')
.post(api.postLogin)
router.route('/api/portfolio')
.post(api.postPortfolio)
.get(api.getPortfolio)
//END ------------
module.exports = router;
Next, my api.js:
var util = require('util');
const backend = require('./portfolio.js');
exports.postPortfolio = function(req,res) {
backend.insertPortFolio(req.body, function(err, result) {
res.json({ result: result, error:err });
});
}
exports.getPortfolio = function(req,res) {
backend.getPortfolio(req, function(err, result) {
global.GLB_PORTFOLIO = result;
res.json({ portfolio: result, error: err });
});
}
exports.postLogin = function(req,res) {
backend.findUserByEmail(req.body.email, function(err, result) {
console.log("API: SESSION IS: " + req.session.isLoggedIn);
if(err || result === null) {
req.session.isLoggedIn = false;
} else {
req.session.isLoggedIn = true;
}
req.session.save();
res.json({ user: result, error: err });
});
}
The session variable is always undefined even after the save(). What am I doing wrong?

Resources