POST method does not work properly Node.js and express

Asked

Viewed 137 times

0

good evening, by way of tests I created a small API to understand its functioning, however when running the POST method I found that it only returns me the empty keys:

[
{}
]

The correct thing would be to return me like this: (when I run GET after POST)

  [
    {
        "name": "Leandro",
        "id": "1"
    }
  ]

I thought it could be my code but I took the one from the class to test and got the same result, I tried to give permission to more in the manipulations of the files but it did not solve, if someone knows or who has already been through so all help is welcome, remembering that I am beginner in Node.js:

Follows my code:

index js.

const express = require('express')
const bodyParser = require('body-parser')

const usersRoute = require('./routes/usersRoute')
const port = 3000

const app = express()

app.use(bodyParser.urlencoded({ extended: false }))

usersRoute(app)

app.get('/', (req, res) => res.send('Olá mundo!'))

app.listen(port, () => console.log(`Express rodando na porta ${port}`)) 

usersRoute.js:

const fs = require('fs')
const { join } = require('path')

const filePath = join(__dirname, 'users.json');

const getUsers = () => {
    const data = fs.existsSync(filePath)
        ? fs.readFileSync(filePath)
        : []

    try {
        return JSON.parse(data);
    } catch (e) {
        return [];      
    }
};

const saveUser = (users) => fs.writeFileSync(filePath, JSON.stringify(users, null, '\t'));

const userRouter = (app) => {

    app.route('/users/:id?')
        .get((req, res) => {
            const users = getUsers()
            res.send({ users })
        })
        .post((req, res) => {
            const users = getUsers()

            users.push(req.body)
            saveUser(users)

            res.status(201).send('OK')
        })
        .put((req, res) => {
            const users = getUsers()
            saveUser(users.map(user => {
                if (user.id === req.params.id) {
                    return {
                        ...user,
                        ...req.body
                    }
                }

                return user
            }))

            res.status(200).send('OK')
        })
        .delete((req, res) => {
            const users = getUsers()
            saveUser(users.filter(user => user.id !== req.params.id))

            res.status(200).send('OK')
        })
}

module.exports = userRouter

and the POST method I run with Postman:

localhost:3000/users?name=Lucas&id=1
  • localhost:3000/users?name=Lucas&id=1 If you’re having problems like this That’s not how it goes

  • I do the POST and then run the GET to see the return, my doubt is why the POST does not insert the data?

  • You are creating your own abstractions of how an api should work, your code does not look like a traditional api developed in express. There is no way to validate opinion on its architecture.

  • this example of code I took from this https://github.com/hmschreiner/node-express, I’m starting Node.js, if you have any references to pass me examples.

  • You are going wrong so it does not have the result you expect ... this API the JSON file is edited locally.

  • Behold that question to better understand how REST Apis work.

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.