Задать вопрос
@DaniilRuss

При отправки формы регистрации, пишет ошибку в консоль, что не так?

При отправки формы регистрации, данные заносятся в бд, но пишет ошибку в консоль и не переадресовывает на нужный компонент (Main).

Ошибка:
Error: No default engine was specified and no extension was provided.
    at new View (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/view.js:61:11)
    at Function.render (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/application.js:570:12)
    at ServerResponse.render (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/response.js:1012:7)
    at exp.signup (/Users/daniilboyko/Desktop/quiz/quiz/server/app/controllers/authcontroller.js:4:9)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)
    at /Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:275:10)
    at SessionStrategy.strategy.pass (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/authenticate.js:343:9)
    at SessionStrategy.authenticate (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/strategies/session.js:75:10)
    at attempt (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/authenticate.js:366:16)
    at authenticate (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/authenticate.js:367:7)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:317:13)
    at /Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/index.js:275:10)
    at initialize (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/passport/lib/middleware/initialize.js:53:5)
    at Layer.handle [as handle_request] (/Users/daniilboyko/Desktop/quiz/quiz/node_modules/express/lib/router/layer.js:95:5)


app/routes/auth.js

const authController = require('../controllers/authcontroller');
 
 
module.exports = function(app, passport) {
 
    app.get('/signup', authController.signup);
 
    app.get('/signin', authController.signin);

    app.get('/main', authController.main);

    app.post('/signup', passport.authenticate('local-signup', {
            successRedirect: '/main',
 
            failureRedirect: '/signup'
        }
 
    ));
}


app/controllers/authcontroller.js

let exp = module.exports = {};
 
exp.signup = function(req, res) {
    res.render('signup');
}

exp.signin = function(req, res) {
    res.render('signin');
}

exp.main = function(req, res) {
 
    res.render('main');
 
}


app/config/passport/passport.js

const bCrypt = require('bcrypt-nodejs')

module.exports = function(passport, user) {
	const User = user;
	const LocalStrategy = require('passport-local').Strategy;

	passport.use('local-signup', new LocalStrategy(
		{
			usernameField: 'email',
			passwordField: 'password',
			passReqToCallback: true 
		},
	
		function(req,email, password, done) {
			let generateHash = function(password) {
				return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null); 
				};
		User.findOne({
			where: {
				email: email
			}
		}).then(function(user) {
			if (user)
			{
				return done(null, false, {
					message: 'That username is already taken'
			});
			} else {
					let userPassword = generateHash(password);
					const data =
							{
									email: email,
									password: userPassword,
									username: req.body.username
							};
					User.create(data).then(function(newUser, created) {
							if (!newUser) {
								return done(null, false);
							}
							if (newUser) {
								return done(null, newUser);
							}
						});
				}
		});
		}
	));

	passport.serializeUser(function(user, done) {
    done(null, user.id);
	});

	// deserialize user 
passport.deserializeUser(function(id, done) {
	User.findByPk(id).then(function(user) {
			if (user) {
					done(null, user.get());
			} else {
					done(user.errors, null);
			}
	});
});
}


server.js

const express = require("express");
const path = require("path");

const app = express();
const passport   = require('passport')
const session    = require('express-session')
const bodyParser = require("body-parser");

const env = require('dotenv');

// For Body Parser
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,"../public")));

// For Passport
app.use(session({ secret: 'keyboard cat',resave: true, saveUninitialized:true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

//Models
const models = require("./app/models");

//Routes
const authRoute = require('./app/routes/auth.js')(app,passport);
//load passport strategies
require('./config/passport/passport')(passport, models.user);
 
//Sync Database
models.sequelize.sync().then(function() {
    console.log('Nice! Database looks fine')
}).catch(function(err) {
    console.log(err, "Something went wrong with the Database Update!") 
});

app.listen(4000,function(){
	console.log("Started listening on port", 4000);
})


Компонент регистрации:

import React, { Component } from 'react'
import axios from 'axios'
import {
  Form,
  Input,
  Button,
} from 'antd';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};
const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 8,
    },
  },
};


const onFinish = values => {
	axios.post('/signup', {
		username: values.username,
		email: values.email,
		password: values.password
	})
	.then(function (response) {
		console.log(response);
	})
	.catch(function (error) {
		console.log(error);
	});
	console.log('Received values of form: ', values);
};

export default class SignUp extends Component {
	styles = {
		wrap: {
			height: "100%",
			display: "flex",
			justifyContent: "center",
			alignItems: "center"
		},
	
		formStyle : {
			width: "500px",
		},
	}
	render() {
		return (
			<div style={this.styles.wrap}>
				<Form
					{...formItemLayout}
					name="register"
					onFinish={onFinish}
					scrollToFirstError
					style={this.styles.formStyle}
					> 
					<Form.Item
						name="username"
						label="Имя пользователя"
						rules={[{ required: true, message: 'Введите имя пользователя!', whitespace: true }]}>
						<Input />
					</Form.Item>

					<Form.Item
						name="email"
						label="E-mail"
						rules={[
							{
								type: 'email',
								message: 'Неправильно введен E-mail!',
							},
							{
								required: true,
								message: 'Введите E-mail!',
							},
						]}
					>
					<Input />
					</Form.Item>

					<Form.Item
        		name="password"
						label="Пароль"
						rules={[
							{
								required: true,
								message: 'Введите пароль!',
							},
						]}
						hasFeedback>
						<Input.Password />
					</Form.Item>

					<Form.Item
							name="confirm"
							label="Подтвердить пароль"
							dependencies={['password']}
							hasFeedback
							rules={[
								{
									required: true,
									message: 'Подтвердите пароль!',
								},
								({ getFieldValue }) => ({
									validator(rule, value) {
										if (!value || getFieldValue('password') === value) {
											return Promise.resolve();
										}
										return Promise.reject('Пароли не совпадают!');
									},
								}),
							]}>
							<Input.Password />
					</Form.Item>

					<Form.Item {...tailFormItemLayout}>
						<Button type="primary" htmlType="submit">
							Регистрация
						</Button>
      		</Form.Item>

				</Form>
			</div>
		)
	}
}
  • Вопрос задан
  • 141 просмотр
Подписаться 1 Простой Комментировать
Пригласить эксперта
Ответы на вопрос 1
@RidgeA
Если планируется использовать серверную генерацию шаблонов то надо подключить правильный движок
Иначе `res.render` не надо использовать
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы