Express + body-parser + Postman: failing to parse POST body - express

As you can see in the code and the attached screenshot, my body is always sent empty, and I have no idea why. Would love some help.
Versions:
"body-parser": "^1.20.1",
"express": "^4.18.2"
Code:
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.get("/blockchain", function (req, res) {});
app.post("/transaction", function (req, res) {
console.log(req.body);
console.log(req.body.amount);
res.sendStatus(200);
});
app.get("/mine", function (req, res) {});
app.listen(3000, function () {
console.log("Listening on port 3000...");
});
Screenshot:

Related

external api results not loading in node.js using https module

whats wrong with my code? its showing no results....although it kinda works when i use google.com as url but in other cases it shows no results*I haven't shared my api key here(appid=)
const express = require('express');
const app = express();
const http = require('http');
app.get("/", function(req, res) {
const url= 'https://api.openweathermap.org/data/2.5/weather?q=london&appid='
http.get(url, function(response){
console.log(response);
// response.on("data", function(data){
// const weatherData = JSON.parse(data);
// const temp = weatherData.main.temp;
// // const weatherDescription = weatherData.weather[0].description;
// res.send(temp)
// })
// res.send('server is sending');
})
})
app.listen(3000, function(req, res){
console.log('Server is alive')
})

Static files inside `public` folder not being served (NextJS custom server using ExpressJS)

I am working on NextJS app. And I have made a custom server using ExpressJS. The problem is when I run the app using the custom server the app cannot find the static files inside the public folder.
Note: I don't have any problem When I run the app using next dev
My server
const express = require('express');
const next = require('next');
const path = require('path');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const prefix = (path = '') => `/:lang(en|tr)?`.concat(path);
app.prepare().then(() => {
const server = express();
server.get(prefix('/'), (req, res) => app.render(req, res, '/', req.query));
server.get(prefix('/agency'), (req, res) => app.render(req, res, '/agency', req.query));
server.get(prefix('/cases'), (req, res) => app.render(req, res, '/cases', req.query));
server.get(prefix('/blog'), (req, res) => app.render(req, res, '/blog', req.query));
server.get(prefix('/contact'), (req, res) => app.render(req, res, '/contact', req.query));
server.get(prefix('/image.png'), (req, res) => app.render(req, res, '/public/images/avatar01.jpg', req.query));
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
It is because you are not implementing a fallback for when there is no match:
server.all('*', async (req, res) => {
return handle(req, res);
}
will handle all the other routes for you (API routes, public/static folder, etc).

expressjs req.body is empty

Banging my head on this. in Express app, my get request works fine. However attempting to POST results passes an empty req.body.
here is my file tree:
index.js:
const express = require('express');
const apiRoute = require('./routes/api/index.js');
const bodyParser = require('body-parser');
// const morgan = require('morgan');
const app = express();
app.use(function(req, res, next) {
if (req.headers['content-type'] === 'application/json;') {
req.headers['content-type'] = 'application/json';
}
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/api', apiRoute);
app.listen(3000);
routes/api/index.js
const express = require('express');
const router = express.Router();
const entityRoute = require('./entity');
router.use('/entity', entityRoute);
module.exports = router;
routes/api/entity.js:
const express = require('express');
const router = express.Router();
const db = require('../../database');
router.get('/', function(req, res) {
db.select().from('entity').then(function(data) {
res.send(data);
});
});
router.post('/', function(req, res) {
console.log(req.body);
res.send(req.body);
});
module.exports = router;
Adding my Postman request in response to comment:
I have been over this numerous times, checked body-parser docs and other SO answers and can't figure this out.
following the comments, submitting json body works. screenshot below:
Not sure why this doesnt work the other way...

expressJS routing issue, simple stuff not resolving

I've recently moved all my route code into separate files, but now my route resolution is spotty. Here's a simple example -
My app.js
const express = require('express');
const app = express();
var dataLoader = require('./routes/dataLoader');
app.all( '/api/load', dataLoader);
My dataLoader.js
const express = require('express');
const router = express.Router();
router.get('/api/load', (req, res) => {
res.send('Hello Loader...');
});
router.get('/api/load/bob', (req, res) => {
res.send('Hello Loader - Bob...');
});
router.get('/api/load/jim', (req, res) => {
res.send('Hello Loader - Jim...');
});
module.exports = router;
/api/load works fine, while /api/load/jim and /api/load/bob both result in:
Cannot GET /api/load/jim (or Cannot GET /api/load/bob, respectively)
I user app.all() instead of app.use() because I was having an issue resolving the main path "/api/load", the use of all seemed to fix that, but now I am not sure.
"engines": {
"node": "^8.9.1"
},
"dependencies": {
"bluebird": "^3.5.1",
"body-parser": "^1.15.1",
"express": "^4.13.4",
"mongoose": "4.9.8"
}
any suggestions?
When you do this:
app.all( '/api/load', dataLoader);
And, then in the dataLoader router, you define routes like this:
router.get('/api/load', (req, res) => {
res.send('Hello Loader...');
});
What you're actually doing is defining a route for api/load/api/load which is likely not what you want. The paths are cumulative.
The app.use() statement should have whatever common prefix applies to your entire router and then the paths on the router itself should be relative to that. In addition, you should use using app.use(), not app.all() for a router.
So, in your case, change the dataLoader router to this:
// whole router is configured at /api/loader
const router = require('express').Router();
router.get('/', (req, res) => {
res.send('Hello Loader...');
});
router.get('/bob', (req, res) => {
res.send('Hello Loader - Bob...');
});
router.get('/jim', (req, res) => {
res.send('Hello Loader - Jim...');
});
module.exports = router;

Express.js, req.params not being called

So i have been racking my brain for quite awhile now trying to figure this out and I'm still having issues.
So i define a route like this:
var home = require('./routes/home');
var app = express();
app.use('/home/:client', home);
And my home.js code looks like this:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.render('homeview', { title: 'Welcome',
user: username});
});
router.get('/:client', function(req, res, next) {
var theClient = req.params.client;
console.log(theClient)
});
module.exports = router;
And then when i try to go to this URL:
http://www.localhost:3000/home/client
Nothing happens. For some reason it never gets to the second router.get and never logs anything. Anyone notice whats wrong?
Working solution # https://github.com/rmjoia/expressRoutes
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
homeRouter = require('./home');
app.use('/home', homeRouter);
app.route('/')
.all(function (request, response, next) {
// Do some plumbing stuff
next();
})
.get(function (request, response, next) {
response.send('OK GET - Hello Stack Overflow');
next();
});
app.listen(port, function (error) {
if (error) {
console.error(error.message);
}
else {
console.info('Server up and running. Listening on port ' + port);
}
})
home.js
var express = require('express');
var homeRouter = express.Router();
var router = (function (router) {
// define the home page route
router.get('/', function (req, res) {
res.send('home route - homepage');
});
// define the about route
router.get('/:client', function (req, res) {
res.send(req.params.client);
});
return homeRouter;
})(homeRouter);
module.exports = router;