Why i can't create a username?

Tell us what’s happening:
I can’t pass this test:
" I can create a user by posting form data username to /api/exercise/new-user and returned will be an object with username and _id ."

Your code so far

const userName = ;

app.post("/api/exercise/new-user", (req, res) => {
//set up
const { username } = req.body;
const name = { username: username, _id: shortId.generate() };
const usedName = userName.find(f => f.username === username);

// user not put the name
if (username.length <= 0) {
return res.send(“Path username is required.”);
}

// name is too long
if (username.length > 17) {
return res.send(“username too long”);
}

//name have already taken
if (usedName) {
return res.send(“username already taken”);
}
userName.push(name);
//finish
res.json(name);
});
Your browser information:

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

Challenge: undefined

Link to the challenge:

1 Like

I looked into FreeCodeCamp’s inputs for the username and they all look similar to the following:

fcc_test_15882440219

That’s longer than 17 characters and according to your code, no JSON response will be returned if the input has length of more than 17.

if the input has length of more than 17, JSON will return “username too long”
this is a condtion:

if (username.length > 17) {
return res.send(“username too long”);
}
I have tried it and it worked

1 Like

True, it works but it’s not the kind of response that the challenge wants. It’s not stated in the user stories that you need to check if the username is longer than 17 characters. Adding to that, return res.send("") returns a text not a JSON.

Implicitly, FCC wants you to return res.json(name) even if the input is longer than 17 characters.

You can try this yourself: try putting the res.json(name) before the ‘must not be longer than 17 characters’ if block and you’ll see that the test passes.

Like so:

// user not put the name
if (username.length <= 0) {
return res.send("Path username is required.");
}
  
res.json(name);
  
// name is too long
if (username.length > 17) {
return res.send("username too long");
}

I might be wrong here but that’s what I think.

1 Like

oh, it worked. But when i put:
if (username.length > 17) {
return res.send(“username too long”);
}
after res.json(name) the condition above isn’t working

1 Like

If you want it to work and at the same time pass the test, you’ll need to make your condition less strict. Maybe make it invalid to have a username that is longer than 20. This is because the test input (example: fcc_test_15882440219 ) will be 20 characters; if that doesn’t work, try 25.

Once you’ve changed the condition, put res.json(name) at the end again like before.

Your code is actually fine but only in this challenge, it will not pass because the test input is of a specific length. Outside of FCC, feel free to make your own validity condition e.g. 17,18, etc.

1 Like