Conditional API in Java Script

Asked

Viewed 51 times

-2

I’m new to Nodejs with Javascript, I got a ready example and I just want to add a condition in the body of the API type: If that value exists it shows the message in the API call via Insonmia or Postman and does not let include.

Código no VSCode

const express = require('express')
const server = express()

server.use(express.json())


const users = ["aa", "bb", "cc", "ddd"]

server.get('/users', (req, res) => {

return res.json(users)
})

server.post('/users', (req, res) => {
    const { name } = req.body
    users.push(name)
       if (name == "aaaa") {
        console.log("Registro existente.")

      return res.json(users)
  
})

server.listen(3000)

Chamada API
{
"name": "aa"
}

via 

1 answer

0


You could check before including the element in the array.

By detecting that the element already exists, simply send the error message.

server.post('/users', (req, res) => {
    const { name } = req.body
    if (name && users.includes(name)) {
        res.json({"msg": "Registro existente"})
        return 
    } else if (name) {
        users.push(name)
    }
    res.json(users)      
})

The else if is necessary to prevent the insertion of the null in the array users, if the key is not sent name in the request.body

Documentation of Array.includes

  • 1

    Very grateful... It worked super well..

Browser other questions tagged

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