1

To learn Node.js I'm using VS Code Win10 to create an express Simple Client Request. The problem I'm running into is when I try to send an error 404 the Simple client request returns the text 'object object'. Non-of the attempts to return a not found message works. Can you let me know what is wrong with the below get function

Thanks

router.get('/accounts/:user', (req, res) => { 
    const user = req.params.user; 
    console.log('at 2 ' + user);  **<<-- works**
    const account = db[user];
    if (!account) {
        console.log(user + ' does not exist'); **<<-- works**
        return res.json('user  does not exist'); **<<-- works**
        // return res.status(404).send({ message: 'Route'+req.url+' Not found.' }); **<<-- does not works**
        return res.status(404).json(  { error: 'user  does not exist'}    ); **<<-- does not works**
    }
    return res.json(account);   **<<-- works**
});
11
  • you should have received an error stating something like you are attempting to set the status header after response is sent to client Commented Feb 3, 2022 at 4:46
  • I don't follow what you mean. when is the status to be sent? the the function the line which does not work is ' return res.status(404).send('user does not exist');' router.get('/accounts/:user', (req, res) => { const user = req.params.user; const account = db[user]; if (!account) { return res.status(404).send('user does not exist'); } return res.json(account); }); Commented Feb 4, 2022 at 5:57
  • I'm saying the function is being returned on line return res.json('user does not exist'); so line return res.status(404).json( { error: 'user does not exist'} ); is not being called. And if you remove the return from previous line you will get the attempting to set status after response is sent error Commented Feb 4, 2022 at 19:46
  • with 404 errors the client expects the message response to be of type string. If you respond with json({ error: '....'}) the client reads an object (the json) and in that another object (error), so outputs object object. Use .send('message') like in the answer below Commented Feb 4, 2022 at 19:51
  • return res.status(404).send('user does not exist'); <<-- does not work Commented Feb 5, 2022 at 0:10

1 Answer 1

1
router.get('/accounts/:user', (req, res) => { 
    const user = req.params.user; 
    console.log('at 2 ' + user);  **<<-- works**
    const account = db[user];
    if (!account) {
        console.log(user + ' does not exist'); **<<-- works**
        return res.status(404).send('user  does not exist'); **<<-- works**
    }
    return res.json(account);   **<<-- works**
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.