When using ExpressJS and body-parser req.body is empty - javascript

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
oracledb.autoCommit = true;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();
router.use('/' , function(req, res , next) {
console.log('Something is happening.');
next();
})
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/insert')
.post(function(req, res) {
console.log(req.body);
console.log(req.body.c1);
console.log(req.body.c2);
});
app.use('/api', router);
app.listen(port);
In the example above ,when I try to log req.body it is returned as empty along with any of its properties.
EDIT: Maybe unrelated but when I try to test this REST API with a extension like Postman , it just keeps processing indefinately. ( Same thing happens with extension called DHC Rest)

Related

Express route isn't executed when JSON file is requested

I defined a route in my Express app that supposed to execute a line of code then return a JSON file, but what happens is that the file is returned, but the line of code isn't executed.
This is the server code:
var express = require('express');
var body_parser = require("body-parser");
var path = require('path');
server = express();
server.use(body_parser.json());
server.use(body_parser.urlencoded({ extended: true }));
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
Inside index.html there is only a script tag defined like:
<body>
<script>
$(document).ready(function(){
$.getJSON("/request.json", function(data) {
console.log(data)
});
})
</script>
</body>
I can see the content of request.json file in chrome console, but the expected message "File "request.json" requested" isn't displayed on server's terminal.
Why the route isn't being executed?
The express.static is called before the /request.json route and already returns the file.
Use this:
const express = require('express');
const bodyParser = require("body-parser");
const path = require('path');
server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.get("/request.json", function(req, res) {
console.log('File \"request.json\" requested.')
res.sendFile(__dirname + "/request.json")
});
server.use(express.static(path.join(__dirname, '/')));
server.get("/", function(req, res) {
res.sendFile("index.html");
});
server.listen(80, function() {
console.log("Server listening on port 80");
});
You can write custom static middleware. Can write logic to not to serve file[exclude].
Note: Note recommend from me, better change route name of /response.json
var express = require("express");
var path = require("path");
var app = express();
var statics = express.static(path.join(__dirname, "/"));
function customServe(secure) {
return function (req, res, next) {
console.log(req.path);
if (req.path != "/response.json") return statics(req, res, next);
return next();
};
}
app.use(customServe());
app.get("/response.json", (req, res) => {
console.log("something...");
res.send({ json: "json" });
});
app.listen(8080, () => console.log("working on 8080"));

node js express app.get and app.post does not work

i wrote a code sample for express js and it is working but when I use app.post or app.get instead of app.use the code does not work and the ide (webstorm) does not recognize the app.post or app.get too
is it replaced with something in the newer versions of express or something?
here is my code:
const express = require('express');
let app = express();
app.use('/addp',(req,res,next)=>{
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({extended:true}));
//next line does not work
//if I use app.use it will work fine
app.get("/product",(req,res)=>{
console.log(req.body);
res.redirect('/');
})
app.use('/',(req,res)=>{
res.send("<h1>done</h1>")
})
app.listen(3000);
Your code is working fine. For the print body, you should have to use bodyParser in express js.
const express = require('express');
let app = express();
var bodyParser = require('body-parser')
app.use('/addp', (req, res, next) => {
res.send("<form action='/product' method='post'><input type='text' name='entry'><button type='submit'>add</button></form>")
})
app.use(express.urlencoded({ extended: true }));
app.use(
bodyParser.json({
limit: "250mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "250mb",
extended: true,
parameterLimit: 250000
})
);
app.get("/product", (req, res) => {
res.send("Get Request")
})
app.post("/product", (req, res) => {
console.log("-------------")
console.log(req.body);
console.log("-------------")
res.send("Post Request")
})
app.use('/', (req, res) => {
res.send("<h1>done</h1>")
})
app.listen(3000);
It is this:
app.route('/product/').get(function (req, res) {
If u want to add multiple routes let's say api, u will do this:
In some module api.js:
const apiRoutes = express.Router();
apiRoutes.get('/some', () => {});
apiRoutes.post('/some', () => {});
Then let's say your server:
app.use('/api', apiRoutes);

Routing an Invalid Request to a 404 Error Page

I'm trying to build a server that user will be able to enter these valid paths:
localhost:9090/admin
localhost:9090/project1
and in case the user enters anything else invalid such as these the user will be redirected to root and then to the default path localhost:9090/404.html:
How do I do it?
this is my code:
app.js
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})
route.js
'use strict';
var express = require('express');
var app = express();
var router = express.Router();
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index');
});
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
res.render('c:/monex/myprojects/' + name +'/index');
});
app.use(function(req, res, next){
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
});
module.exports = router;
Expressjs has a pretty cool way of handling errors and routing them.
1/ To Confirm if project exists
We use the filesystem module to confirm if it exists, using the access API, you can read more on the module at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html
var fs = require('fs') // We'll need to ask the filesystem if it exists
var projectname = 'myfolder';
// Excerpt from your code, but Modified
router.get('/:projectname', function(req, res) {
var name = req.params.projectname;
fs.access(name, fs.constants.F_OK, function(err) {
if(!err) { // directory exists
res.render('c:/monex/myprojects/' + name + '/index');
return;
}
// Directory does not exist
next({statusCode: 404});
})
});
2/ To route the error properly
From the above code, we said anytime directory does not exist in nodejs, call next with an error object, i.e next(err), the difference between next() and next(err) is that there are two types of middlewares in expressjs, the first is:
app.use("/", function(req, res, next) {})
while the second is
app.use("/", function(err, req, res, next) {})
The difference between the two is that, the first one is a normal middleware that routes requests through. But the second is called a error handling middleware. Anytime that next function is called with an argument, express jumps to route it through error handling middlewares from there on. So, to solve your problem.
You will want to solve this at the app level so that all across all routers, you can have 404 pages delivered.
In app.js
function Error404(err, req, res, next) {
if(err.statusCode === "404") {
res.status(404).render('c:/monex/404.html', {title: "Sorry, page not found"});
}
// YOu can setup other handlers
if(err.statusCode === "504") {}
}
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(Error404);
REFERENCES
http://expressjs.com/en/guide/error-handling.html
https://www.safaribooksonline.com/blog/2014/03/12/error-handling-express-js-applications/
https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
Try changing the signature of your 404 handler function
Express will use it as an error handler of just add change function parameters to: (err, req, res, next)
I also got it fixed by adding this to my app.js
app.use(function (err, req, res, next) {
res.render('c:/monex/505.html', { status: 500, url: req.url });
})
making it look like this
var express = require('express');
var app = express();
var path = require('path');
var routes = require('c:/monex/routes/index');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(express.static('c:/monex/admin'));
app.use('/', routes);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(function (err, req, res, next) {
res.render('c:/monex/404.html', { status: 404, url: req.url });
})
var server = app.listen(9090, function () {
var host = server.address().address
var port = server.address().port
console.log("MonexJS listening at", port)
})

What's wrong with my express.router().get method?

I'm trying to follow this tutorial, in which the author provides a sample code:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
And I tweaked it a little bit and here is my code:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
var router = express.Router();
router.get('/', function(req, res, next) {
res.json({ message: 'Hello World!' });
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
The server runs perfectly but when I visit localhost:8081, I get the following message on my browser: Cannot GET /
What am I doing wrong here?
Since you added app.use('/api', router);
And your route is router.get('/', function(req, res, next) { res.json({ message: 'Hello World!' }); });
Then to access '/' you need to request with /api/
Update: If you have set the port on in env use that port or else you should be able to access using localhost:8081/api/
Hope it helps !
The above comment is correct.
You have added prefix '/api' to your local server and all incoming request will be http://localhost:<port>/api/<path>
app.use('/api', router);
If you want to access like this (without prefix) http://localhost:<port>/<path>
Please update your code to
app.use(router);

Express.js req.body is returning nothing

I am learning node and express to create an api for an angular app I will be creating.
When I try and post something the req.body seems to be blank.
This is my server.js file
'use strict';
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
router = require('./api'),
bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost/my_db');
app.use(bodyParser.json());
app.use('/api', router);
app.get('/', function(req, res) {
res.render(__dirname + '/index.jade');
});
app.listen(3001, function() {
console.log('Listening on port 3001');
});
and this is my api/index.js file:
'use strict';
var express = require('express'),
Todo = require('../models/todo'),
router = express.Router();
router.get('/todos', function(req, res) {
Todo.find({}, function(err, todos) {
if(err) {
return console.log(err);
}
res.json({todos: todos});
});
});
router.post('/todos', function(req, res) {
var todo = req.body;
res.json({todo: todo});
});
module.exports = router;
when I use postman to post this to http://localhost:3001/api/todos:
{
'name': 'Walk the Dog',
'completed': false
}
my response is:
{
"todo": {}
}
I can't see why this would be blank, any help is appreciated.
UPDATE
Turns out I was posting text in postman instead of JSON.
use this in your server.js file
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

Categories

Resources