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.
Related
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 am trying to post using restler and return the response to client but response never returns .Below is code I am using and response is just hanging
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var rest = require('restler');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = 3001; // can also get it from process.env.PORT
var router = express.Router();
//this is like interceptor for every route to validate all requests, logging for analytics
router.use(function (req, res, next) {
console.log('route intercepted');
next(); // make sure we go to the next routes and don't stop here
});
router.get('/', function(req, res) {
res.json({ message: "welcome to restful node proxy layer to business processes" });
});
router.route('/someroute').post(function(req, res) {
rest.postJson('http://localhost/api/sg', req.body).on('complete', function(data, response) {
console.log(response);
}
).on('error', function(data, response) {
console.log('error');
});
});
app.use('/api', router); //all routes are prefixed with /api
app.listen(port);
console.log("server is running magic happens from here");
How do I use multiple router files using express framework?
In my app.js, I have the following code:
var controller = require('./controller/index');
var healthController = require('./controller/health/');
app.use('/', controller);
app.use('/health', healthController);
And controller/index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
And health.js:
var express = require('express');
var router = express.Router();
/* GET health confirmation. */
router.get('/health', function(req, res, next) {
res.send('OK');
});
module.exports = router;
When I hit the http://localhost:8000/, I get the correct page without any problem, however, http://localhost:8000/health results in 404 error.
Thanks in advance.
Assuming the "health.js" resides in "controller" directory, may it be just a typo issue? var healthController = require('./controller/health/'); has a trailing slash (/). Removing it would fly? So it becomes var healthController = require('./controller/health');
Your single node app must have single router object, a router object represents a server in express requiring unique port.
Hence you should create router object in you app.js passing it to all router files.
Code will be like -
app.js
var express = require('express');
var router = express.Router();
var controller = require('./controller/index');
var healthController = require('./controller/health/');
controller(router);
healthController(router);
index.js
module.exports = function(router) {
router.get('/', function(req, res, next) {
res.render('index');
});
}
health.js
module.exports = funtion(router) {
router.get('/health', function(req, res, next) {
res.send('OK');
});
}
See How to include route handlers in multiple files in Express?.
Export an anonymous function that can be "initiated" with a reference to the original express app.
./controller/index.js:
module.exports = function(app) {
/* GET home page. */
app.get('/', function(req, res, next) {
res.render('index');
});
};
./controller/health.js:
module.exports = function(app) {
/* GET health confirmation. */
app.get('/health', function(req, res, next) {
res.send('OK');
});
};
./app.js:
var app = require('express')();
var controller = require('./controller/index');
var healthController = require('./controller/health');
controller(app);
healthController(app);
Change in health.js:
router.get('/health', function(req, res, next) {
res.send('`OK`');
});
to
router.get('/', function(req, res, next) {
res.send('OK');
});
This will work fine check it out.
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;