Friday 19 May 2017

Sending empty {} after form "post" with pug in node.js

I'm trying to pass form data from login page to signin page via post using fetch with this pug code:

form(id="form-login")
    input(type="text", name="email", value="", placeholder="Tu email")
    br
    input(type="password", name="password", value="", placeholder="Tu contraseƱa")
    br
    input(type="submit" value="Conectar")
script.
    const formLogin = document.querySelector('#form-login');
    const formData = new FormData(formLogin);

    formLogin.addEventListener('submit', function(event) {
        console.log('Form Data: ', formData);
        event.preventDefault();
        fetch('/signin', {
            method: 'POST',
            body: formData
        })
        .then(function(res) {
            res.json();
        })
        .then(function(data) {
            console.log(data)
            localStorage.setItem('token', data.token)
        })
    });

The problem is an empty req.body reaching to signin.. After trace it gives this console.log

Form Data:  FormData {}

and also an undefined req.body. If I comment this script and just send it through form adding action="/signin" and method="post", it works and the answer is printed, but calling storage.setItem({ token: <token> }) returns an Uncaught (in promise) TypeError: Cannot read property 'token' of undefined I'm wondering why this script is not sending the data... can't figure out... so any help will be much apreciated.

Signin function:

function signIn (req, res) {    
    if (!req.body.email) return res.status(200).send({message: 'No recibo el usuario'})

    User.findOne({ email: req.body.email }, (err, user) => {

        if(err) return res.status(500).send({ message: err })
        if(!user) return res.status(404).render('login', { title: 'Intenta loguearte de nuevo' })

        user.comparePassword(req.body.password, (error, isMatch) => {
            if (error) return res.status(500).send({ message: error })
            if (!isMatch) {
                return res.redirect('login')
            } else {
                req.user = user
                res.status(200).send({
                    message: 'Te has logueado correctamente',
                    token: service.createToken(user)
                })
                //$window.localStorage.setItem({token: service.createToken(user)}); // NO WORKS
                return res.body = service.createToken(user) // TRYING THIS WITHOUT KNOWLEDGE ABOUT WHAT AM I DOING :O
            }
        })                 
    })
}

Thanks in advance.



via Adolfo Onrubia

No comments:

Post a Comment