인프런 커뮤니티 질문&답변

leewj4242님의 프로필 이미지
leewj4242

작성한 질문수

Node.js 교과서 - 기본부터 프로젝트 실습까지

passport serializeUser/deserializeUser

오류가 나서 질문을 드립니다.

작성

·

364

0

auth.js 입니다.

const express = require('express');
const passport = require('passport');
const bcrypt = require('bcrypt');
const { isLoggedInisNotLoggedIn } = require('./middlewares');
const { User } = require('../models');

const router = express.Router();

router.post('/join'isNotLoggedInasync (reqresnext=> {
  const { emailnickpassword } = req.body;
  try {
    const exUser = await User.find({ where: { email } });
    if (exUser) {
      req.flash('joinError''이미 가입된 이메일입니다.');
      return res.redirect('/join');
    }
    const hash = await bcrypt.hash(password12);
    await User.create({
      email,
      nick,
      password: hash,
    });
    return res.redirect('/');
  } catch (error) {
    console.error(error);
    return next(error);
  }
});

router.post('/login'isNotLoggedIn, (reqresnext=> {
  passport.authenticate('local', (authErroruserinfo=> {
    if (authError) {
      console.error(authError);
      return next(authError);
    }
    if (!user) {
      req.flash('loginError'info.message);
      return res.redirect('/');
    }
    return req.login(user, (loginError=> {
      if (loginError) {
        console.error(loginError);
        return next(loginError);
      }
      return res.redirect('/');
    });
  })(reqresnext); 
});

router.get('/logout'isLoggedIn, (reqres=> {
  req.logout();
  req.session.destroy();
  res.redirect('/');
});

module.exports = router;
app.js 입니다.
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const session = require('express-session');
const flash = require('connect-flash');
const passport = require('passport');
require('dotenv').config();

const indexRouter = require('./routes/page');
const authRouter = require('./routes/auth');

const { sequelize } = require('./models');
const passportConfig = require('./passport');

const app = express();
sequelize.sync();
passportConfig(passport);

app.set('views'path.join(__dirname'views'));
app.set('view engine''pug');
app.set('port'process.env.PORT || 8002);

app.use(morgan('dev'));
app.use(express.static(path.join(__dirname'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(session({
  resave: false,
  saveUninitialized: false,
  secret: process.env.COOKIE_SECRET,
  cookie: {
    httpOnly: true,
    secure: false,
  },
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());

app.use('/'indexRouter);
app.use('/auth'authRouter);

app.use((reqresnext=> {
  const err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use((errreqresnext=> {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

app.listen(app.get('port'), () => {
  console.log(app.get('port'), '번 포트에서 대기중');
});

답변 4

1

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

User.find 대신 User.findOne 하시면 됩니다.

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

한글을 넣고 싶으시면 model에서 sequelize.define의 두 번째 인수(옵션 객체)에 다음 두 개를 넣으셔야 합니다(테이블을 지웠다가 다시 생성하셔야 합니다)

charset:'utf8',
collate:'utf8_general_ci',

0

leewj4242님의 프로필 이미지
leewj4242
질문자

음 일단 auth.js 에서 생기는 오류는 해결하였습니다.

하지만 error.pug에서 생기는 오류와 DB오류가 생기는거 같은대.. 이것들은 어떻게 해야될까요?

DatabaseError [SequelizeDatabaseError]: Incorrect string value: '\xEC\x9D\xB4\xEC\x9B\x90...' for column 'nick' at row 1

    at Query.formatError (C:\Users\DELL\Desktop\nodebird\node_modules\sequelize\lib\dialects\mysql\query.js:244:16)

    at Execute.handler [as onResult] (C:\Users\DELL\Desktop\nodebird\node_modules\sequelize\lib\dialects\mysql\query.js:51:23)

    at Execute.execute (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\commands\command.js:30:14)

    at Connection.handlePacket (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:417:32)

    at PacketParser.onPacket (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:75:12)

    at PacketParser.executeStart (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\packet_parser.js:75:16)

    at Socket.<anonymous> (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:82:25)

    at Socket.emit (events.js:223:5)

    at addChunk (_stream_readable.js:309:12)

    at readableAddChunk (_stream_readable.js:290:11)

    at Socket.Readable.push (_stream_readable.js:224:10)

    at TCP.onStreamRead (internal/stream_base_commons.js:181:23) {

  name: 'SequelizeDatabaseError',

  parent: Error: Incorrect string value: '\xEC\x9D\xB4\xEC\x9B\x90...' for column 'nick' at row 1

      at Packet.asError (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\packets\packet.js:712:17)

      at Execute.execute (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\commands\command.js:28:26)

      at Connection.handlePacket (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:417:32)

      at PacketParser.onPacket (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:75:12)

      at PacketParser.executeStart (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\packet_parser.js:75:16)

      at Socket.<anonymous> (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:82:25)

      at Socket.emit (events.js:223:5)

      at addChunk (_stream_readable.js:309:12)

      at readableAddChunk (_stream_readable.js:290:11)

      at Socket.Readable.push (_stream_readable.js:224:10)

      at TCP.onStreamRead (internal/stream_base_commons.js:181:23) {

    code: 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD',

    errno: 1366,

    sqlState: 'HY000',

    sqlMessage: "Incorrect string value: '\\xEC\\x9D\\xB4\\xEC\\x9B\\x90...' for column 'nick' at row 1",

    sql: 'INSERT INTO `users` (`id`,`email`,`nick`,`password`,`provider`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?,?);',

    parameters: [

      'kitti0418@naver.com',

      '이원제',

      '$2b$12$fas7/Kr7tMyQkL95o2CBPuuJklvekQOqGuRuXPdo9jRgsk60TLwLu',

      'local',

      '2020-06-08 22:16:38',

      '2020-06-08 22:16:38'

    ]

  },

  original: Error: Incorrect string value: '\xEC\x9D\xB4\xEC\x9B\x90...' for column 'nick' at row 1

      at Packet.asError (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\packets\packet.js:712:17)

      at Execute.execute (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\commands\command.js:28:26)

      at Connection.handlePacket (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:417:32)

      at PacketParser.onPacket (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:75:12)

      at PacketParser.executeStart (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\packet_parser.js:75:16)

      at Socket.<anonymous> (C:\Users\DELL\Desktop\nodebird\node_modules\mysql2\lib\connection.js:82:25)

      at Socket.emit (events.js:223:5)

      at addChunk (_stream_readable.js:309:12)

      at readableAddChunk (_stream_readable.js:290:11)

      at Socket.Readable.push (_stream_readable.js:224:10)

      at TCP.onStreamRead (internal/stream_base_commons.js:181:23) {

    code: 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD',

    errno: 1366,

    sqlState: 'HY000',

    sqlMessage: "Incorrect string value: '\\xEC\\x9D\\xB4\\xEC\\x9B\\x90...' for column 'nick' at row 1",

    sql: 'INSERT INTO `users` (`id`,`email`,`nick`,`password`,`provider`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?,?);',

    parameters: [

      'kitti0418@naver.com',

      '이원제',

      '$2b$12$fas7/Kr7tMyQkL95o2CBPuuJklvekQOqGuRuXPdo9jRgsk60TLwLu',

      'local',

      '2020-06-08 22:16:38',

      '2020-06-08 22:16:38'

    ]

  },

  sql: 'INSERT INTO `users` (`id`,`email`,`nick`,`password`,`provider`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?,?);',

  parameters: [

    'kitti0418@naver.com',

    '이원제',

    '$2b$12$fas7/Kr7tMyQkL95o2CBPuuJklvekQOqGuRuXPdo9jRgsk60TLwLu',

    'local',

    '2020-06-08 22:16:38',

    '2020-06-08 22:16:38'

  ]

}

Error: C:\Users\DELL\Desktop\nodebird\views\error.pug:2:1

Declaration of template inheritance ("extends") should be the first thing in the file. There can only be one extends statement per file.

    at makeError (C:\Users\DELL\Desktop\nodebird\node_modules\pug-error\index.js:34:13)

    at error (C:\Users\DELL\Desktop\nodebird\node_modules\pug-linker\index.js:7:30)

    at C:\Users\DELL\Desktop\nodebird\node_modules\pug-linker\index.js:198:9

    at walkAST (C:\Users\DELL\Desktop\nodebird\node_modules\pug-walk\index.js:26:18)

    at C:\Users\DELL\Desktop\nodebird\node_modules\pug-walk\index.js:112:20

    at Array.reduce (<anonymous>)

    at walkAndMergeNodes (C:\Users\DELL\Desktop\nodebird\node_modules\pug-walk\index.js:111:18)

    at walkAST (C:\Users\DELL\Desktop\nodebird\node_modules\pug-walk\index.js:40:19)

    at checkExtendPosition (C:\Users\DELL\Desktop\nodebird\node_modules\pug-linker\index.js:193:3)

    at link (C:\Users\DELL\Desktop\nodebird\node_modules\pug-linker\index.js:19:5)

    at compileBody (C:\Users\DELL\Desktop\nodebird\node_modules\pug\lib\index.js:192:9)

    at Object.exports.compile (C:\Users\DELL\Desktop\nodebird\node_modules\pug\lib\index.js:267:16)

    at handleTemplateCache (C:\Users\DELL\Desktop\nodebird\node_modules\pug\lib\index.js:240:25)

    at Object.exports.renderFile (C:\Users\DELL\Desktop\nodebird\node_modules\pug\lib\index.js:452:10)

    at Object.exports.renderFile (C:\Users\DELL\Desktop\nodebird\node_modules\pug\lib\index.js:442:21)

    at View.exports.__express [as engine] (C:\Users\DELL\Desktop\nodebird\node_modules\pug\lib\index.js:491:11)

    at View.render (C:\Users\DELL\Desktop\nodebird\node_modules\express\lib\view.js:135:8)

    at tryRender (C:\Users\DELL\Desktop\nodebird\node_modules\express\lib\application.js:640:10)

    at Function.render (C:\Users\DELL\Desktop\nodebird\node_modules\express\lib\application.js:592:3)

    at ServerResponse.render (C:\Users\DELL\Desktop\nodebird\node_modules\express\lib\response.js:1012:7)

    at C:\Users\DELL\Desktop\nodebird\app.js:55:7

    at Layer.handle_error (C:\Users\DELL\Desktop\nodebird\node_modules\express\lib\router\layer.js:71:5)

POST /auth/join 500 329.197 ms - 2591

0

leewj4242님의 프로필 이미지
leewj4242
질문자

오류코드 잘 안보이신거 같으니 파일 다시 올려드릴게요

leewj4242님의 프로필 이미지
leewj4242

작성한 질문수

질문하기