Saturday, 6 May 2017

express 4.x bodyparser isn't working

I installed latest version of body-parser(1.17.1) and set my code in proper order as others suggested.

  1. import express

  2. import body-parser

  3. app = express();

  4. app.use(bodyParser.json());

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

but I constantly get error "TypeError: Cannot read property 'password' of undefined".

Actually I can't imagine what the problem is.

I spent almost 10 hours keep tracking solution and I'm almost given up.

Is there any method to get my code work?

Help me some, please...

below is my code

    const express = require('express');
    const path = require('path');
    const session = require('express-session');
    const MySQLStore = require('express-mysql-session')(session);
    const bodyParser = require('body-parser');
    const passport = require('passport');
    const LocalStrategy = require('passport-local').Strategy;
    const pbkdf2Password = require('pbkdf2-password');
    const hasher = pbkdf2Password();
    const mysql = require('mysql');
    const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '10rhrnak',
    database: 'users',
    });
    connection.connect();

    //crawler setting
    const http = require('http');
    const cheerio = require('cheerio');
    const iconv = require('iconv-lite');
    const fs = require('fs');

    const app = express();
    const port = process.env.PORT || '4200';
    app.set('port', port);
    app.listen(port, () => console.log(`API running on localhost:${port}`));

    app.use(express.static(path.join(__dirname, '../dist')));

    app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../dist/index.html'));
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(session({
    secret: '@232t2g23',
    resave: false,
    saveUninitialized: true,
    store: new MySQLStore({
        host: 'localhost',
        port: 3306,
        user: 'root',
        password: '10rhrnak',
        database: 'users',
    })
    }));
    app.use(passport.initialize());
    app.use(passport.session());

    app.post('/auth/register', (res, req) => {

        hasher({password: req.body.password}, (err, pass, salt, hash) => {
            let user = {
                authId: 'local'+req.body.email,
                email: req.body.email,
                password: hash,
                salt: salt,
                displayName: req.body.displayName
            };
            let sql = 'INSERT INTO users SET ?';
            connection.query(sql, user, (err, results) => {
                if(err) {
                    console.log(err);
                    throw new Error("register error!");
                } else {
                    req.redirect('/');
                }
            });
        });   
    });



via 이준형

No comments:

Post a Comment