I'm just starting out and I've got a barebones app here with a routes file ./routes/index.js.
When I browse to http://localhost:3000/index for example index.js is hit but none of the routes match and the program just goes straight through to "return router;". If I browse to http://localhost:3000/ I get the same again.
All the browser does is think about it for a bit and then give me a ERR_CONNECTION_RESET.
app.js
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var flash = require('connect-flash');
mongoose.connect('mongodb://localhost/blah');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(flash());
app.use(require('./routes/index'));
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
function authorize(req, res, next) {
if (true) {
next()
} else {
res.status(403).send('Forbidden')
}
}
module.exports = function(){
router.get('/index', function(req, res) {
res.send('index');
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
router.get('/', function(req, res) {
res.send('root');
});
return router;
}
app.js is missing a line to actually start the server. You need to add this:
app.listen(3000);
Got there in the end... I changed
module.exports = function(){
router.get('/index', function(req, res) {
res.send('index');
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
router.get('/', function(req, res) {
res.send('root');
});
return router;
}
to
router.get('/index', function(req, res) {
res.send('index');
});
router.get('/hello/:name', function(req, res) {
res.send('hello ' + req.params.name + '!');
});
router.get('/', function(req, res) {
res.send('root');
});
module.exports = router;
Related
res.redirect function is used to redirect the user to another page by clicking a button. But the function's not working. Please find the code below.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/failure", function (req, res) {
res.redirect("/");
});
app.post("/success", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function () {
console.log("The server is running at port 3000");
});
Try moving
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});
below your other routes and try calling again
Try changing app.post to app.get:
app.get("/success", function(req, res) {
res.redirect("/");
});
I can't work out where I'm going wrong with this simple routing task. When I go to localhost:3030/staff, I'm getting "Cannot GET /staff" and a 404 error.
Here is my setup.
app.js:
const express = require('express');
const app = express();
const port = process.env.PORT || 3030;
const staffRouter = require('./routes/staffrouter.js');
app.use('/static', express.static(__dirname + './public'));
app.use('./staff', staffRouter);
app.get('/', function(req, res) {
res.render('index.pug');
});
app.listen(port);
I have tried using the paths "/staff" in my GET/POST requests, but that doesn't work, and isn't how it's supposed to work according to the tutorial I'm doing. I'm really stuck.
/routes/staffrouter.js:
var express = require('express');
var router = express.Router();
const staff = require('../staff').staff;
const urlEncoded = (express.urlencoded({ extended: true }));
router.get('/', function(req, res, next) {
res.render('staff.pug', {
deptOptions: staff.populateSelectors('department'),
posOptions: staff.populateSelectors('position'),
empArray: staff.readWriteJSON()
});
});
// Add new staff obj
router.post('/', urlEncoded, function(req, res, next) {
let sObj = req.body;
let dataArray = staff.readWriteJSON();
//console.log('data:', data);
dataArray.push(new staff.Employee(
sObj.fName,
sObj.lName,
sObj.staffNum,
sObj.department,
sObj.position,
sObj.email,
sObj.phone
));
staff.readWriteJSON(dataArray)
res.render('../views/staff.pug', {
deptOptions: staff.populateSelectors('department'),
posOptions: staff.populateSelectors('position'),
empArray: staff.readWriteJSON()
});
});
module.exports = router;
wrong scope change the order
app.use('/static', express.static(__dirname + './public'));
const staffRouter = require('./routes/staffrouter.js');
I'm new to express and used yo-generator to create my project. The problem I'm facing is that routes with:
app.get('/something') are working fine, but
router.get('/something') are not working. I tried to research but could not solve the problem.
Here are my files:
app.js
var fs = require('fs');
var http = require('http');
var path = require('path');
var helmet = require('helmet');
var express = require('express');
var root = path.normalize(__dirname + '/');
var constant = require(root + '/app/util/constants.js');
var config = require(constant.APP_CONFIG_FILE);
var app = express();
app.use(helmet());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
return next();
});
require('./config/express')(app, config);
http.createServer(app).listen(config.WEB_PORT, function() {
console.log('Server listening http on port ' + config.WEB_PORT);
});
module.exports = app;
Lines from express.js
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
app.set('views', config.ROOT + '/app/views');
app.set('view engine', 'ejs');
// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(compress());
app.use(express.static(config.ROOT + '/public'));
app.use(methodOverride());
var controllers = glob.sync(config.ROOT + '/app/controllers/*.js');
controllers.forEach(function(controller) {
require(controller)(app);
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app/controllers/user-ctrl.js
var path = require('path');
var express = require('express');
var router = express.Router();
var root = path.normalize(__dirname + '/../..');
var constant = require(root + '/app/util/constants.js');
var service = require(constant.USER_SERVICE_FILE);
var responseUtil = require(constant.RESPONSE_UTIL_FILE);
module.exports = function(app) {
app.use(constant.USER_PATH, router); // constant.USER_PATH is '/user' (added after alexmac asked)
**// this works**
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
**// This doesn't work**
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
};
/*
GET: /user
*/
router.route('/:page?/limit?/:limit')
.get(function(req, res) {
responseUtil.sendResponse(service.allRecords(req, res), req, res);
});
/*
POST: /user
*/
router.route('/')
.post(function(req, res) {
responseUtil.sendResponse(service.saveRecord(req, res), req, res);
});
/*
GET: /user/1
PUT: /user/1
DELETE: /user/1
*/
router.route('/:id')
.get(function(req, res) {
responseUtil.sendResponse(service.findRecord(req, res), req, res);
})
.delete(function(req, res) {
responseUtil.sendResponse(service.deleteRecord(req, res), req, res);
})
.put(function(req, res) {
responseUtil.sendResponse(service.updateRecord(req, res), req, res);
});
These are the key lines. I've changed the order to try to clarify the intent but that shouldn't change how they behave:
// Create a route for GET /test
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
// Create a route for GET /user/test
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/user', router);
The router is mounted at the path /user so any paths on the router will be relative to /user. In other words, if app is handling requests at http://localhost/test then router will handle http://localhost/user/test.
Change your code with this piece of code
var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.json());
var app = express();
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/route',router);
module.exports = router;
When you want to get use http://localhost:port/route/test
Hope this helps.
I wrote the following code:
var express = require('express');
var router = express.Router();
var app = express();
app.put('/data', function(req, res) {
res.send("OK");
});
app.get('/data', function(req, res) {
console.log(); // What to write here?
});
app.listen(4000);
I sent a PUT request by Postman:
Now, I want to ask what I to write inside the brackets of console.log that the code will print the content stored in the http path?
I want to see the JSON
{"name":"John"}
EDIT: I tried the solution shown in this link:
Node.js - get raw request body using Express:
var express = require('express');
var router = express.Router();
var app = express();
var bodyParser = require('body-parser');
app.use(function(req, res, next) {
req.rawBody = '';
req.on('data', function(chunk) {
req.rawBody += chunk;
});
next();
});
app.use(bodyParser());
app.put('/data', function(req, res) {
res.send("OK");
});
app.get('/data', function(req, res) {
console.log(res.rawBody);
res.end();
});
app.listen(4000);
I still didn't get what I expected.
In my server.js file I have below url mappings:
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
In training.controller file I have mapped below way:
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
when call "/registerCourse","/getCourses","/getCourseDetails" throwing error saying:
"Cannot GET /getCourses"
Server.js -
require('rootpath')();
var express = require('express');
var app = express();
var session = require('express-session');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var config = require('config.json');
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({ secret: config.secret, resave: false, saveUninitialized: true }));
app.use('/login', require('./controllers/login.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
app.use('/getCourseDetails', require('./controllers/training.controller'));
app.get('/', function (req, res) {
return res.redirect('/app');
});
var server = app.listen(3000, function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
training.controller.js-
var config = require('config.json');
var express = require('express');
var app = express();
var router = express.Router();
var trainingService = require('services/training.service');
app.use(router);
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
router.get('/getCourseDetails', getCourseDetails);
module.exports = router;
function registerCourse(req, res) {
console.log(" registerCourse called ()"+req.body);
trainingService.register(req.body);
}
function getCourses(req, res) {
trainingService.getCourses()
.then(function (data) {
res.json(data);
})
.catch(function (err) {
res.status(400).send(err);
});
}
function getCourseDetails(req, res) {
console.log(req.body)
}
Solution:
Your route will be:
/registerCourse
/getCourses
/getCourseDetails
app.js
app.use('/login', require('./controllers/login.controller'));
app.use('/app', require('./controllers/app.controller'));
app.use('/',require('./controllers/training.controller'));
/*
app.use('/registerCourse', require('./controllers/training.controller'));
app.use('/getCourses', require('./controllers/training.controller'));
app.use('/getCourseDetails', require('./controllers/training.controller'));
-- removed
*/
training.controller.js
var config = require('config.json');
var express = require('express');
// var app = express(); -- removed
var router = express.Router();
var trainingService = require('services/training.service');
// app.use(router); -- removed
router.post('/registerCourse', registerCourse);
router.get('/getCourses', getCourses);
router.get('/getCourseDetails', getCourseDetails);
module.exports = router;
function registerCourse(req, res) {
console.log(" registerCourse called ()"+req.body);
trainingService.register(req.body);
}
function getCourses(req, res) {
trainingService.getCourses()
.then(function (data) {
res.json(data);
})
.catch(function (err) {
res.status(400).send(err);
});
}
function getCourseDetails(req, res) {
console.log(req.body)
}
In server.js you can use
app.use('/', require('./controllers/training.controller'));
app.use('/', require('./controllers/training.controller'));
app.use('/', require('./controllers/training.controller'));
and then try calling your
"/registerCourse","/getCourses","/getCourseDetails"