how can i save data that i get from a POST request in a express server into a BED doing a post to an URL?

Viewed 143

i am new here and i am new using node JS. in an interview for a job the people ask me to do this: i have to make my own express server, make a post request and get a name, lastname and dni, validate them, and finally i have to save them into a data base doing a post to the URL (for example lets said that the url is "http://formulario-14.com/personas.json") i have no idea how to save that data that i get in my post request. if you could give me a hand i would really appreciate it. i am not sure if i have to make another app.post, or maybe do a request inside my app.post, i dont know.

code:

const express = require('express')
const app = express()

const {body, validationResult} = require('express-validator')
const { errorFromList } = require('verror')

app.use(express.json())
app.set('view engine','ejs')
app.use(express.urlencoded({extended:true}))

app.get('/', (req, res)=>{
    res.render('index')
})

app.post('/registrar',[
    body('name','send name')
    .isAlpha()
    .withMessage('only char')
    .isLength({ max: 20 })
    .withMessage('no more then 20 char'),
    
    body('lastName','send lastname')
    .isAlpha()
    .withMessage('only char')
    .isLength({ max: 20 })
    .withMessage('no more then 20 char')
    .notEmpty()
    .withMessage('is obligatorily'),

    body('dni','send dni')
    .isLength({ min: 5 })
    .withMessage('no less then 5 numbers')
    .isLength({ max: 10 })
    .withMessage('no more then 10 numbers')
    .isNumeric()
    .withMessage('only numbers')
    .notEmpty()
    .withMessage('is obligatorily')

], (req, res)=>{
    const errors = validationResult(req);
    const cuerpo = req.body

    if (!errors.isEmpty()){
        return res.status(400).json({ errors: errors.array()});
    }
    else {
        res.status(201).send(cuerpo);
    }
})

app.listen(3000, ()=>{
    console.log('Nico server')
})
0 Answers
Related