Exercise Tracker: can't parse by bodyparser.text

Tell us what’s happening:
Hello all,

I’ve been working on ‘create a new user’ part.
Somehow bodyparser.text doesn’t parse user input.
The console.log(req.body) result is:

{
messageFormat: undefined,
stringValue: ‘"{username: undefined}"’,
kind: ‘string’,
value: {username: undefined},
path: ‘username’,
reason: null,
valueType: ‘Object’
}

Your code so far

// basic setting
require(‘dotenv’).config()
const express = require(‘express’);
const cors = require(‘cors’)
const bodyParser = require(‘body-parser’);
const mongoose = require(‘mongoose’);
const mySecret = process.env[‘MONGO_DB’]
const app = express();

app.use(cors())
app.use(express.static(‘public’))
app.get(’/’, (req, res) => {
res.sendFile(__dirname + ‘/views/index.html’)
});
app.use(bodyParser.text());

//db setting
mongoose.connect(mySecret);
let myMongo = mongoose.connection;

// create schema & model
let userSchema = mongoose.Schema({
username: {type: String}
});

let Username = mongoose.model(‘username’, userSchema);

// create username & return json
app.post(’/api/users’, function(req, res) {
console.log(req.body);
let userInput = { username: req.body };

Username.create(userInput, function(err, username){
if(err) return console.log(err);
});

Username.find({username: userInput}, function(err, foundUsername){
if(err) return console.log(err);
console.log(foundUsername[0]._id);
res.json({ username : userInput,
_id : foundUsername[0]._id});
});

});

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36

Challenge: Exercise Tracker

Link to the challenge:

Try using body parser to parse JSON instead of text.

Also, post a link to your live project on repl.it or similar so that people can see the code and run the project themselves and you’ll get more help.

1 Like

Thank you for your reply!

Unfortunately, I’m struggling with the same issue even after I changed the part as bodyParser.json…

the result of console.log(req.body) turns out to be {}, like there’s nothing can parse.

and I assigned string type for username model, I got cast error which said I put object({}) into where string type is supposed to be.

btw, that’s my replit link, feel free to correct mine!

"boilerplate-project-exercisetracker - Replit

Typical usage is

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

I think one of the practice exercises covers the particulars; if not, the body parser documentation will fill in the details. The short version is you have to decode and parse the body data. This output

turns out to be part of an error message from mongoose, so once you’re getting your username in to the code, you can fix the mongoose error.

Thanks!

by adding bodyParser.urlencoded, it works.
I found the user input for ‘username’ at req.body.username