如何:发送并获取" formdata"用哈巴狗和javascript

时间:2017-05-20 17:39:12

标签: javascript node.js forms express pug

在哈巴狗中得到这个表格:

extends layout

block login
    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');

formLogin.addEventListener('submit', function(event) {
    const formData = new FormData(formLogin);
    console.log('Contenido de Formulario: ', 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)
    })
});

处理程序功能正在接收空req.body

这个问题延伸my last question 我希望有人知道这里发生了什么,提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为这可能就是答案,因为我已经解决了这个问题。

block login
    form(id="login" action="/signin" method="post")
        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")

路线代码:

router.post('/signin', usercontrol.signIn)

控制器代码:

const User = require('../models/User')
const service = require('../services')
const bcrypt = require('bcrypt-nodejs')


function signUp (req, res) {
    console.log('Registrando usuario: ', req.body)
    const user = new User({
        email: req.body.email,
        displayName: req.body.displayName,
        password: req.body.password
    })

    user.save((err) => {
        if (err) res.status(500).send({ message: `Error al crear el usuario: ${err}`})

        return res.status(200).send({ token: service.createToken(user) })
    })
}

function signIn (req, res) {    
    console.log('Tratando de loguear con req: ', req.body.email)

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

    User.findOne({ email: req.body.email }, (err, user) => {
        console.log('Respuesta de búsqueda', user)

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

        let userPwd = req.body.password
        let dbPwd = user.password
        console.log('Pwd Usuario: ', req.body.password, 'Pwd Base de Datos: ', user.password)

        bcrypt.compare(userPwd, dbPwd, (error, isMatch) => {
            if (error) return res.status(500).send({ message: error })
            if (!isMatch) {
                console.log('La contraseña No es correcta !isMatch: ', !isMatch)
                return
            } else {
                req.user = user
                res.status(200).send({
                    message: 'Te has logueado correctamente',
                    token: service.createToken(user)
                })
            }
        })        
    })
}

module.exports = {
    signIn,
    signUp
}