Can't read body parameter in Express for POST - javascript

I am having trouble access the body parameters of a request with express:
const bodyParser = require('body-parser');
const cors = require('cors');
const express = require('express');
const app = express();
const port = 8000;
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
const corsOptions = {
origin: 'http://localhost:8000'
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, () => console.log(`Listening on http://loclalhost:${port}`));
The route I am trying to hit is: http://loclalhost:8000/api/auth/signup
Within the route I try to access the body like so:
const user = new User({
username: req.body.username,
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8)
});
However I am getting the error TypeError: Cannot read property 'username' of undefined, what am I doing wrong here?

I guess the problem is not in reading the body parsed data, as it says user and not username. Can you please share the complete code instead.

A suggestion
Change :
app.use(bodyParser.urlencoded({ extended: true }))
to
app.use(bodyParser.urlencoded({ extended: false }))
and use x-www-form-urlencoded

Hmm well my guess is the order how you wrote your code. Imagine the code goes from the top to the bottom, so you access the app routes before you parse the body. Try it like this, swap the order:
const corsOptions = {
origin: 'http://localhost:8000'
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
Its also a common way to use the express router like this for example:
const routes = require("./routes/routes.js");
app.use(routes);

Related

Express js get request is showing on the html page

Im new in express.js so i would like to know why when I'm sending a data to client the data is showing in the browser but I'd like to send it in preview please can you take a look what I do wrong?
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.get('/getProducts', (req,res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type','application/json');
res.json(obj);
});
first you need install dependencies like body-parse cors, then you need listen port like this
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/getProducts', (req, res) => {
const obj = {
data: 'jojo'
};
res.set('Content-Type', 'application/json');
res.json(obj);
});
app.listen(3000)

express.js get method cannot get req.body value

I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine

expressjs display post data returns an empty object

So I'm developing a chat server using expressjs and socketio and decided to create an admin where backend built in with the node chat server itself.
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
So upon login data submission, I tried to display the post data from the login form but it returns me an empty object {}
console.log(req.body);
Tried to do req.params but same result .Any help, ideas is greatly appreciated.
I tried running your code and its working fine. Maybe the way you are calling the API is not right
To support content-type: x-www-form-urlencoded you should use
app.use(bodyParser.urlencoded({ extended: true }));
and to support content-type: application/json you should use
app.use(bodyParser.json());
I think you are using form-data, for that neither of these will work. For that you may want to use formidable package. We should use form-data content type only when we are sending any images/file.
And body-parser has been merged with express. You can directly use this now
app.use(
express.json(),
express.urlencoded({ extended: false })
);
I think this might be a right solution for your problem, as everything seems to be right in your code, the error might be caused by the way you are calling the API and you are setting the headers:
https://stackoverflow.com/a/25904070/12090205
const express = require("express");
const app = express();
const port = 3700;
let io = require('socket.io').listen(app.listen(port));
let socketList = io.sockets.server.eio.clients;
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/login', function(req, res) {
res.render('login', { title: 'Login | Argos Chat' });
});
app.post('/login', function(req, res) {
console.log(req.body);
});
I checked Its Working.

Req.body is empty object

I dont know why did? Help me debug! Please
i try console.log(req.body) and i get {} (empty object)
I tried many ways but I still couldn't understand why.
I tried using middleware but it didn't work either
const express = require("express");
const app = express();
const pug = require('pug');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine' , 'pug');
app.set('views', './views');
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('./db.json')
const db = low(adapter)
app.get('/todos/create', (req, res)=> {
res.render('create');
});
app.post('/todos/create', (req,res)=> {
console.log(req.body);
db.get('todos').push(req.body).write();
res.redirect('/todos');
});
app.listen(3000);```
this is file create.bug
```h1 Create New List
form(action="/todos/create", method="post", enctype="multipart/form-data")
.form-group
label(for="id") Id
input#id(name="id" type="text")
.form-group
label(for="text") Text
input#text(name="text" type="text")
button Create```
----------
The body-parser module is responsible for parsing data ; you use it in your code, but I don't even see where you import it. You need at least to import it at the top of your file
var bodyParser = require('body-parser')
See others example of use here : https://www.npmjs.com/package/body-parser

Graphql: Must provide query string

I have a simple express graphql server:
const schema = require('./schema');
const express = require('express');
const graphqlHTTP = require('express-graphql');
const cors = require('cors')
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/graphql', graphqlHTTP(req => {
return ({
schema,
pretty: true,
})
}));
const server = app.listen(9000, err => {
if (err) { return err; }
console.log(`GraphQL server running on http://localhost:${9000}/graphql`);
});
And my request looks like:
Any help?
(Please don't close it as duplicate because the other post does not provide enough info on how the user solved it)
You need to specify application/json in your Content-Type header -- you currently have text/plain. You've included the body parser middleware on the server, but it relies on that header in your request to know when it needs to actually parse the response into JSON.

Categories

Resources