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: