In node express when I try to access the post value from the form it shows request body undefined error.
Here is my code,
http.createServer(function(req, res) {
var hostname = req.headers.host.split(":")[0];
var pathname = url.parse(req.url).pathname;
if (pathname==="/login" && req.method ==="POST") {
console.log("request Header==>" + req.body.username );
}).listen(9000, function() {
console.log('http://localhost:9000');
});
Please any one help me to find why the request body shows undefined.
Enable body-parser middleware first
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
If you're not using express for the web server and just plain http. Use the body module.
Related
Login.js - react component.
I printed the JSON.stringify(credentials) object and it is valid but when i print the req.body in the server it is empty.
//sending a post request to the server with the username and password inserted by the user.
async function loginUser(credentials) {
console.log(JSON.stringify(credentials));
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(response => {
console.log(response);
})
};
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
you have to use a middleware to parse the json body in the post request,
you have not used bodyParser.json() as middleware
below is your updated code
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
I tried to make a golden book width nodeJS. So I use body-parser to get my form's values and it works until I try to verify if my form is empty by this way :
app.post('/', (request, response) => {
if(request.body.message === undefined) {
console.log('Message : ' + request.body.message);
}
When I try to run my server and test my form by pushing informations, the loading of the page is infinite.
Can you help me please ?
Here, the full code :
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
// moteur de template
app.set('view engine','ejs');
// MIDDLEWARE
app.use('/assets', express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
// ROUTE
app.get('/', (request, response) =>{
response.render('pages/index');
});
app.post('/', (request, response) => {
if(request.body.message === undefined) {
console.log('Message : ' + request.body.message);
}
});
app.listen(8080);
Your request is infinite, because you never finish it.
You can do it by simple
response.end()
in your request handler or if you want to return something to a client, then you can use
response.send({message: 'hello there'})
Unfortunately I get an empty body: {} in the request object, when I POST something to my api via Insomnia (configuration Form Form URL Encoded Header Content-Type: application/x-www-form-urlencoded):
Here is my express code:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.send("Hallo");
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
What am I doing wrong? And also what would I have to change in my code if I'd configure Insomnia to Form as JSON, Header Content-Type: application/json ?
For accessing request body use body-parser middleware and for sending the response in JSON format use res.json()
https://www.npmjs.com/package/body-parser
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.json({"message":"Hallo"}); //update here
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
available in Express v4.16.0 onwards:
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
I'm trying to extract POST data using a NodeJS script (with Express). The body is received, but I cannot seem to extract the variable from it when posting to the page with Postman. The variable is undefined, although I have used the same code I found in different questions. I have correctly installed Nodejs, express and body-parser.
To clarify, I'm posting form-data with Postman with key 'username' and value 'test'.
Anyone knows what I'm doing wrong?
var https = require('https');
var fs = require('fs');
var app = require('express')();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var httpsOptions = {
key: fs.readFileSync('/home/privkey.pem'),
cert: fs.readFileSync('/home/cert.pem'),
};
var server = https.createServer(httpsOptions, app);
server.listen(3000);
app.get('/', function(req, res) { //On get
res.send(req.method);
});
app.post('/', function(req, res) { //On post
res.send( req.body.username );
});
I guess it has to do with the encoding:
JSON:
you have to set a header with Content-Type: application/json and
add the encoding in express before the route :
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Otherwise you can just use the option x-www-form-urlencoded and set the inputs
Not able to get any data in the following post request , any suggestions ?
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var urlEncodedParser = bodyParser.urlencoded({extended:false});
var app = express();
// add Service
app.post('/api/service/addService',urlEncodedParser, (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});
Will you try this
var app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
after that write your code -
app.post('/api/service/addService', (request, result) => {
if (!request.body) return result.sendStatus(400);
console.log(request.body);
console.log(request.params);
});