Back End Development and APIs Projects - Exercise Tracker

Tell us what’s happening:

I tried to tackle the third test “The returned response from POST /api/users with form data username will be an object with username and _id properties.” first, and I believe that I fulfilled it, but it does not pass. The other tests don’t pass as well, but this is expected as I am only focusing on the third test for now.

###Your project link(s)

Here is my index.js file:

const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();

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

// I referred to the answers at https://stackoverflow.com/questions/44554038/typeerror-cannot-read-property-of-undefined-expressjs-post;
// specifically those from ram and Khurram.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post('/api/users', function(req, res) {
  var username = req.body.username;
  res.json({ username: username, _id: "5fb5853f734231456ccb3b05"});
});





const listener = app.listen(process.env.PORT || 3000, () => {
  console.log('Your app is listening on port ' + listener.address().port)
})

solution: https://freecodecam-boilerplate-0qn9q0b5hy9.ws-us108.gitpod.io

githubLink: https://3000-freecodecam-boilerplate-0qn9q0b5hy9.ws-us108.gitpod.io

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:123.0) Gecko/20100101 Firefox/123.0

Challenge Information:

Back End Development and APIs Projects - Exercise Tracker

Hi there. Do you know what the shape of the object is the client is getting back? Like what exact values are on it. It might help figure out why it isn’t working.

Hi, I guess you have to develop the POST endpoint; so far it looks you getting the username value and responding the username and some random ID.

Noet: Avoid using “var” instead use “const”

First, get the username from form:
const username = req.body.username;

Next, create new user with: User.create({ username: username });

Here I destructured the object:
const { username, _id } = await User.create({ username: username });

OR you can do like this too:
const result = await User.create({ username: username });
const username = result.unsername;
const _id = result._id;

Finally, respond back the client with the username and ID:
res.json({ username: username, _id: _id });

if you have doubts check my repo: boilerplate-project-exercisetracker/index.js at main · gernesto14/boilerplate-project-exercisetracker · GitHub

i have the same prob …

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.