The relevant part of my app.js is as follows
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
var routes = require('./config/routes);
app.use('/', routes);
My route file is:
var express = require('express');
var router = express.Router();
var upgradesController = require('../../app/controllers/upgrades.server.controller');
// This should receive POST requests
router.post('/api/upgrades/device', upgradesController.create);
module.exports = router;
And finally my controller is
exports.create = function(req, res) {
res.send(req.body);
}
But this sends nothing. It's always an empty JSON value. I'm using PostMan for testing:
What is happening?
You're sending form-data, switch to x-www-form-urlencoded instead. You can also send "raw", and input valid JSON.
Related
So, when i make a Post request to the ExpressJS api with postman (localhost:8080?test=test), i should get this from the api: {test: test} or something right? But i get this: {}.
Heres my code:
Api:
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(cookieParser())
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
app.use(express.static(__dirname + '../../../src/'));
app.get('/*', (req,res) => res.sendFile(path.join(__dirname)));
const server = http.createServer(app);
server.listen(port,() => {
console.log('Running...');
})
app.post('/', function(req,res){
let data = JSON.stringify(req.body);
console.log(data);
res.send(data)
})
Can you help me?
Edit:
Printscreen
Inside post endpoint you are console logging req.body which is actually {}. According to the endpoint you are receiving data as query params. Therefore you have to use req.query instead of req.body to capture the data.
for some reason I can see my req.body in my express server on my route
req body is [Object: null prototype] { '{"password":"xxxxxxxx"}': '' }
but when I log req.body.password (the object key) I get
req body is undefined
here's my index router for reference in my express app
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
const path = require('path');
/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {
console.log('req body is',req.body.password)
res.send("passconfirmed");
});
module.exports = router;
To access the content of the body, Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
You need to install a body-parser package.
npm i body-parser --save
Now import body-parser in your project.
It should be called before your defined route functions.
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser')
const path = require('path');
app.use(bodyParser.json());
app.use(bodyparser.urlencoded({ extended : true }));
/* GET adminPanel. */
router.post('/authenticate', function(req, res, next) {
console.log('req body is',req.body.password)
res.send("passconfirmed");
});
module.exports = router;
If you're using body-parser
You have to enable the body parser to work, before using parsed data in you routes.
In your main module where you import all your libs, you need to declare express to use body-parser middleware.
const express = require('express')
const bodyparser = require('body-parser')
const app = express()
app.use(bodyparser.json())
app.use(bodyparser.urlencoded({ extended : true }))
...
//here comes your routes
After including the bodyparser middleware you can use parsed data in your routes.
Notice that if you're using express version >= 4.16, body parser comes bundled with express. You just have to use change your code to:
const express = require('express')
const app = express()
app.use(express.json()); //this line activates the bodyparser middleware
app.use(express.urlencoded({ extended: true }));
Doing so you can safely remove body-parser package.
I got this error "Cannot GET /api/data"
it s working good on my local host , but when I upload it to server it show me this error,
this is a simple code for testing that also show me the same .
my index page
const express = require('express');
const bodyparser = require('body-parser');
const mysql = require('mysql');
const port = 4000;
const route = require('route');
const data = require('./routes/data.js');
const app = express();
app.use(bodyparser.json());
// parse application/x-www-form-urlencoded
app.use(bodyparser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyparser.raw());
// parse text
app.use(bodyparser.text());
app.use('/data', data);
app.listen(port, () => {
console.log("working");
});
/routes/data.js file
const express = require('express');
const router = express.Router();
const add = require('../classes/insert');
const bodyparser = require('body-parser');
var con = require('../Modules/connection');
const app = express();
app.use(bodyparser.json());
// parse application/x-www-form-urlencoded
app.use(bodyparser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyparser.raw());
// parse text
app.use(bodyparser.text());
app.get("/",(req, res)=>{
res.send("hello");
});
module.exports = router;
app.use('/data', data)
This will only work on /data route. If you want this work on /api/data, use the following snippet.
app.use('/api/data', data)
this error may be comming because of the file path. Try using __dirname in spite of ./ and also check your file structure.
Hope this works.
When I send a POST request using postman to localhost:8080/api/newUser with request body:
{name: "Harry Potter"}
At server end console.log(req.body) prints:
{ '{name: "Harry Potter"}': '' }
server.js
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
router.use(function(req, res, next) {
next();
});
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
app.use('/api', router);
app.listen(8080);
What am I doing wrong?
In express.js the order in which you declare middleware is very important. bodyParser middleware must be defined early than your own middleware (api endpoints).
var express = require('express');
var app = express();
var router = express.Router();
var bodyParser = require('body-parser');
app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies
router
.route('/newUser')
.post(function(req, res) {
console.log(req.body);
});
app.use('/api', router);
app.listen(8080);
Change the request header
'Content-Type':'application/json'
So that bodyParser can parse the body.
*That is what works for me. i am using angular 2+ with express(body-parser)
I spent quite a bit of time trying to figure out how to pass objects from Axios as key-value pairs and eventually decided to go with an alternative because setting the Content-Type: "application/json" retuned an empty object.
If the above options don't work for you, I would consider:
Extracting the key (which should contain the entire
object)
Parsing the key
Accessing the values of the newly created objects
This worked for me:
var obj = (Object.keys(req.body)[0])
var NewObj = JSON.parse(obj)
var name = apiWords["Key1"]
var image = apiWords["Key2"]
Here is my code.
server.js
var express = require('express'),
bodyParser = require('body-parser'),
log = require('./libs/log')(module),
api = require('./libs/api.js'),
app = express();
// settings
app.set('port', 5000);
// to process post requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// routes
rawQuestionRouter = require('./routes/rawQuestionRoutes.js');
app.use('/rawQuestions', rawQuestionRouter);
and routes/rawQuestionRoute.js:
var express = require('express');
var routes = function() {
var rawQuestionRouter = express.Router();
rawQuestionRouter.route('/test')
.post(function(request, response) {
log.debug(request.body);
response.send('raw question saved');
});
return rawQuestionRouter;
}
module.exports = routes;
Update:
When I make a POST request on '/rawQuestions/test' the server don't respond. Why?
You're exporting the routes function, which is not a router (it returns one, but that's not the same).
There are several solutions:
// server.js
app.use('/rawQuestions', rawQuestionRouter());
Or:
// routes/rawQuestionRoute.js
module.exports = routes();
Or just remove the entire routes function altogether and export the router instance directly.