Cannot GET / request - javascript

My router does not seem to work on remote server but it works perfects on local server.
I've tried with so many methods to solve it but yet no results.
At first, the error that gave me had something to do with phusion, hence if the if statement in app.js and now it gives no error in log, but on browser it shows: cannot get /
Please help me solve, code snippets below:
app.js
const http = require('http');
const app = require('./app')
if (typeof(PhusionPassenger) != 'undefined') {
PhusionPassenger.configure({ autoInstall: false });
}
const port = process.env.PORT || 9100;
const server = http.createServer(app);
server.listen(port, ()=>console.log(`Server running on port ${port}`));
index.js
if (process.env.ENV !== "development") {
require('dotenv').config();
}
// console.log(process.env)
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const helmet = require('helmet');
// Routes imports
const admin_users = require('./routes/admin/users');
const admin_locations = require('./routes/admin/locations');
// const admin_products = require('./routes/admin/products');
const admin_deliveries = require('./routes/admin/deliveries');
const admin_payments = require('./routes/admin/payments');
const admin_dashboard = require('./routes/admin/dashboard');
const admin_orders = require('./routes/admin/orders');
const users = require('./routes/users');
const products = require('./routes/products');
const deliveries = require('./routes/deliveries');
const payments = require('./routes/payments');
const tickets = require('./routes/tickets');
// const files = require('./routes/files');
const cards = require('./routes/cards');
let app = express();
app.set('trust proxy', true);
app.use(helmet());
// app.use(express.staticProvider(__dirname + '/public'));
// view engine setup
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Access-User, X-Access-Token,Authorization");
// next();
if ('OPTIONS' === req.method) {
//respond with 200
return res.status(200).json({});
// next();
}
else {
//move on
next();
}
});
// Routes
app.get('/', (req,res,next)=>{
res.send('server is up and running');
})
app.use('/admin/users', admin_users);
app.use('/admin/locations', admin_locations);
// app.use('/admin/products', admin_products);
app.use('/admin/deliveries', admin_deliveries);
app.use('/admin/payments', admin_payments);
app.use('/admin/orders', admin_orders);
app.use('/dashboard', admin_dashboard);
app.use('/users', users);
app.use('/products', products);
app.use('/deliveries', deliveries);
app.use('/payments', payments);
app.use('/tickets', tickets);
// app.use('/files', files);
app.use('/cards', cards);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
require("./scheduler")
// catch 404 and forward to error handler
app.use(function(req, res, next) {
let 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');
});
require('./server');
module.exports = app;

You should remove this code below
app.get('/', (req,res,next)=>{
res.send('server is up and running');
})
and replace it with
app.get('/', (req,res,next)=>{
res.send('server is up and running');
})
Place it below
app.set('view engine', 'ejs')

Related

Req has no body when posting with Postman

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.

getting RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined in express app

I am getting the above error when running the following code in my express app. When I go to localhost:3000/cards.
This is in my cards.js file.
const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;
router.get('/', (req, res) => {
res.render('card', {
prompt: cards[0].question,
hint: cards[0].hint
});
});
module.exports = router;
This is the code in my app.js file.
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('view engine', 'pug');
const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');
app.use(mainRoutes);
app.use('/cards', cardRoutes);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error');
});
app.listen(3000, () => {
console.log('The application is running on localhost:3000!');
});
Any help would be appreciated. Basically, I am trying to incorporate a json file into the express app and it is coming up with this error.
Set a default status in your error handler middleware if error does not contain the property status.
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.set('view engine', 'pug');
const mainRoutes = require('./routes');
const cardRoutes = require('./routes/cards');
app.use(mainRoutes);
app.use('/cards', cardRoutes);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.locals.error = err;
const status = err.status || 500;
res.status(status);
res.render('error');
});
app.listen(3000, () => {
console.log('The application is running on localhost:3000!');
});

Pass HTML to nodejs server

I am trying to pass html from a client(angularjs) app to server side (nodejs), i am trying to access the html via the req.body, but the object is always empty({}).
So on the client side, I just call the api passing the html:
generatePDF() {
const htmlBlock = document.getElementById("templateArea");
const htmlObj = {"element": htmlBlock};
this.pdfService.generatePDF(htmlObj).subscribe(
(response) => {
console.log("pdf generated");
},
(error) => {
console.log(error);
}
);
}
the angular service does a post call.
everything fine, since it reaches the api, but then i try to access via console.log the req.body, that shows me always empty, any suggestion (i have the bodyparser already).
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 router = express.Router();
var app = express();
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.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next();
});
app.use('/',require('./routes/index'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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')));
// 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 route:
var express = require('express');
var router = express.Router();
var pdfGenerator = require('../controllers/pdfGenerator');
router.post('/pdfURL', pdfGenerator.pdfToUrl );
module.exports = router;
the controller
var express = require('express');
var router = express.Router();
var fs = require('fs');
var pdf = require('html-pdf');
//var html = fs.readFileSync('./test/businesscard.html', 'utf8');
var options = { format: 'Letter' };
module.exports = {
pdfToUrl: function(req,res,next) {
console.log(req.body);
pdf.create('<div style="background-color:blue">a simple text</div>', options).toFile('./businesscard.pdf', function(err, res) {
console.log("asd"); // { filename: '/app/businesscard.pdf' }
if (err) return console.log(err);
console.log("asd"); // { filename: '/app/businesscard.pdf' }
});
}
};

Express API routes returning undefined response

I'm using express to serve API endpoints to my redux app. When I attempt to make get requests from the client side to these endpoints, I get a response with undefined body property. When I use Postman to test the endpoint, it returns the expected result with a body property that is JSON data.
Here's my code
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 users = require('./routes/users');
var routes = require('./routes/index.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
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, 'client')));
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);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
module.exports = app;
Every other answer to this question says nothing more than "move the lines adding bodyParser middleware in front of the lines where you instantiate the routes", which I am already doing.

Extremely Long TTFB on localhost (Node/Express)

I'm experiencing extremely long TTFB on my localhost node/express server.
On average each request's(including static resource) TTFB is around 1s, occasionally up to 7s(I guess this is NOT normal)
What could cause this long TTFB and how to improve?
Could it be my fault for configing express wrong?
Here is my app.js:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var favicon = require('serve-favicon');
var morgan = require('morgan')
//Router files
var all = require('./api/all');
var admin = require('./api/admin');
var student = require('./api/student');
var teacher = require('./api/teacher');
var course = require('./api/course');
var forum = require('./api/forum');
var group = require('./api/group');
var board = require('./api/board');
// App Setup
var app = express();
// View engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(morgan(':remote-addr [:date[clf]] :user :method :url :status :response-time ms',{
skip: function (req, res) {
//var noUser = (req.AV.user === undefined);
//return noUser;
return true;
}
}));
app.use(favicon(__dirname + '/public/favicon.ico'));
// Load Cloud Code
//app.use(cloud);
//Express Middleware
app.use(methodOverride('_method'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname+'/public'));
//The Route
app.get('/', function(req, res) {
res.send('./public/index.html');
});
//Routers
app.use('/api',all);
app.use('/api/admin',admin);
app.use('/api/student',student);
app.use('/api/teacher',teacher);
app.use('/api/course',course);
app.use('/api/forum',forum);
app.use('/api/group',group);
app.use('/api/board',board);
//404 Handler
app.use(function(req, res, next) {
//console.log("NOT FOUND: "+req.url);
var err = new Error('Not Found');
err.status = 404;
res.render('notfound.jade');
//next(err);
});
// error handlers for different env
if (app.get('env') === 'development') {
console.log("dev env");
app.use(function(err, req, res, next) {
res.status(err.status || 500);
if(res.status===500){
console.log(err);
//console.log(err.stack.split("\n"));
}
res.send({
message: err.message,
error: err
});
});
}
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err.message);
res.send({
message: err.message,
error: {}
});
});
module.exports = app;
ps:I'm using node 4.0.0 and latest chrome

Categories