React-Express:未指定默认引擎,也未提供扩展名

时间:2019-02-27 02:59:43

标签: reactjs express next.js

我正在阅读教程,试图理解为什么出现错误:未指定默认引擎并且未提供扩展名。错误。我在Express上使用Next.js

我的文件是这样的:

register.js

import Page from '../layouts/page';
import AuthenticationForm from '../components/AuthenticationForm';
import { REGISTER } from '../assets/constants';

const Register = (props) => (
    <Page>
        <AuthenticationForm view={REGISTER} />
    </Page>
);

export default Register;

Express Server代码: approuter.js

const Router = require('express').Router;
const AuthController = require('../controllers/AuthController')
const passport = require('passport');
const strategies = require('../services/passport');


passport.use(strategies.localLogin);
passport.use(strategies.jwtLogin);
const requireSignIn = passport.authenticate("local", { session: false });

class AppRouter {
    constructor() {
        this.router = Router();
        this.buildRoutes();
    }

    buildRoutes() {
        this.router.get("/hello", (req, res) => {
            res.send("hello");
        });
        this.router.get("/about", (req, res) => {
            res.render('/about');
        });
        this.router.get("/register", (req, res) => {
            res.render('/register');
        });

        this.router.post('/register', requireSignIn, AuthController.signin);
    }
}

const appRouter = new AppRouter();
module.exports = appRouter.router;

AuthenticationForm.js

import React, { Component } from 'react';
import { Form, Button, Input } from 'antd';
import fetch from 'isomorphic-unfetch';
import { LOGIN, REGISTER } from '../assets/constants';

const RegisterFields = props => (
    <>
        <Form.Item>
            {props.getFieldDecorator("firstName", {
                rules: [
                    {
                        required: true,
                        message: "Please enter your first name for registration"
                    }
                ]
            })(<Input name="firstName" placeholder="First Name" />)}
        </Form.Item>
        <Form.Item>
            {props.getFieldDecorator("lastName", {
                rules: [
                    {
                        required: true,
                        message: "Please enter your last name for registration"
                    }
                ]
            })(<Input name="lastName" placeholder="Last Name" />)}
        </Form.Item>
    </>
);

class AuthenticationForm extends Component {
    constructor(props) {
        console.log("entered AuthForm");
        super(props);
        this.state = {
            email: "",
            password: "",
            loginError: false,
            success: false
        };

        this.view = {
            login: {
                path: "/signin",
                name: "Login"
            },
            register: {
                path: "/register",
                name: "Register"
            }
        };

        if (this.props.view === LOGIN)
            this.viewManager = this.view.login;
        else if (this.props.view === REGISTER)
            this.viewManager = this.view.register;

    }

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((error, values) => {
            fetch(this.viewManager.path, {
                method: "post",
                headers: {
                    'Accept': "application/json",
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(values)
            }).then(async res => await res.json())
                .then(data => {
                    if (data.token) {
                        localStorage.setItem("quickApptToken", data.token);
                    }
                    this.setState({success: true})
                }).catch(error => {
                    if (error) this.setState({ loginError: true });
                });
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="inline" onSubmit={this.handleSubmit}>
                {this.state.loginError && <p>LOGIN ERROR! </p>}
                {this.state.success && (
                    <p>{this.viewManager.name} successful</p>
                )}
                {this.props.view === REGISTER && (
                    <RegisterFields getFieldDecorator={getFieldDecorator} />
                )}
                <Form.Item>
                    {
                        getFieldDecorator("email", { rules: [{ required: true, message: "Please enter a valid email!" }] })(
                            <Input name="email" placeholder='Enter your email' />
                        )
                    }
                </Form.Item>
                <Form.Item>
                    {
                        getFieldDecorator("password", { rules: [{ required: true, message: "Please enter your Password" }] })(
                            <Input name="password" type='password' placeholder='Enter your password' />
                        )
                    }
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        {this.viewManager.name}
                    </Button>
                </Form.Item>
            </Form>
        )
    }
}

export default Form.create({ name: "authForm" })(AuthenticationForm);

server.js

const express = require('express');
const session = require('express-session');
const uuid = require('uuid');
const bodyParser = require('body-parser');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV || "development";
const PORT = process.env.PORT || 3000;

const app = next({ dir: './app', dev });
const handle = app.getRequestHandler();
const getRoutes = require('./routes');
const routes = getRoutes();
const AppRouter = require('./routes/AppRouter')

const models = require('./db/model');

app
    .prepare()
    .then(() => {
        const server = express();
        server.use(
            session({
                secret: uuid.v1(),
                name: "sessionId",
                resave: true,
                saveUninitialized: true
            })
        );
        server.use(bodyParser.urlencoded({ extended: true }));
        server.use(bodyParser.json());

        server.use(AppRouter);

        server.get('*', (req, res) => {
            const parsedUrl = parse(req.url, true);
            const { pathname, query = {} } = parsedUrl;
            /**
             * Pull in front end routes, check requests against those routes
             */
            const route = routes[pathname];
            if (route) {
                return app.render(req, res, route.page, query);
            }
            handle(req, res);
        });

        models.sequelize.sync().then(function () {
            server.listen(PORT, err => {
                if (err) throw err;
                console.log("Server started on Port: ", PORT)
            });
        });

    }).catch(err => {
        console.error(err);
        process.exit(1);
    });

所以当前正在发生的事情是,如果我从index.js中删除,并放入一些html代码或文本,则该链接可以正常工作,但是如果我使用authenticationform,则该链接将不起作用,如果我去了直接到本地主机:3000 /注册我得到没有默认引擎指定错误。

0 个答案:

没有答案