Hello
I am just starting the certification project and cannot get past the first bit.
The first test/task is "You can POST
to /api/users
with form data username
to create a new user."
Pretty straightforward. I added the code below (between comments) but I just cannot get a value out of req.body.username
.
My code:
const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
// MY CODE ---------------------------------
app.post("/api/users", async (req, res) => {
let username = req.body.username; // <<--the culprit
if (username === ""){
res.json({error: "please enter a user name"})
}
console.log(username);
res.json(username)
});
// MY CODE ---------------------------------
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
The resulting error message:
/workspace/boilerplate-project-exercisetracker/index.js:14
let username = req.body.username; // <<--the culprit
^
TypeError: Cannot read properties of undefined (reading 'username')
I have tried req.body
and req.body.username
… I even tried req.params
and req.params.username
out of desparation but nothing!
The relevant HTML form:
<form action="/api/users" method="post">
<h2>Create a New User</h2>
<p><code>POST /api/users</code></p>
<input id="uname" type="text" name="username" placeholder="username" />
<input type="submit" value="Submit" />
</form>
I’m either missing something dreadfully obvious or maybe there’s something wrong with the test setup?