当尝试渲染我的第二页(服务)时,我发现它只是呈现主页。我是表达和节点的新手,所以我看不出原因。
import config from './config';
import apiRouter from './api';
import express from 'express';
const server = express();
import {home, services} from './serverRender';
server.set('view engine', 'ejs');
server.get('/', (req, res) => {
var contents = home();
res.render('index', {
content: contents
});
});
server.get('/services', (req, res) => {
var contents = services();
res.render('services', {
content: contents
});
});
server.use(express.static('public'));
server.listen(config.port, () => {
console.info('Express listening on port', config.port);
});
serverRender.js:
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import Home from './src/components/Home'
import Services from './src/components/Services'
import config from './config';
const home = () => {
ReactDOMServer.renderToString(
<Home />
);
};
const services = () => {
ReactDOMServer.renderToString(
<Services />
);
};
export {home, services}
index.ejs和services.ejs(他们有相同的代码)
<%- include('header') -%>
<div id="root"><%- content -%></div>
<%- include('footer') -%>
config.js
const env = process.env
export const nodeEnv = env.NODE_ENV || 'development'
export default {
port: env.PORT || 8080,
host: env.HOST || '0.0.0.0',
get serverUrl() {
return `http://${this.host}:${this.port}`;
}
};
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(
<App initialContests={window.initialData.contests} />,
document.getElementById('root')
);
更新
我已经发现,由于某种原因,express只是渲染index.js。我认为这可能与我的webpack配置有关,该配置将此文件列为条目。我不知道如何解决它,任何帮助将不胜感激。
答案 0 :(得分:0)
使用Express with a template engine时,您需要使用Express服务器上的'views'
设置声明您的观看位置。
还要确保在需要的路线之前(即静态内容)分配中间件。 Express自上而下评估中间件和路由,因此如果您将静态内容放在路由之后,并且该路由依赖于静态资源,则在路由需要它之前不会使其成为静态。
const express = require('express')
const path = require('path')
const server = express()
const port = process.env.PORT || 1337
// res.render() will now look in './views' for the templates
server.set('views', path.join(__dirname, 'views'))
server.set('view engine', 'ejs')
server.use(express.static(path.join(__dirname, 'public')))
// Your Router Middleware/Routes goes here
server.listen(port, () => {
console.log(`Listening on ${port}`)
})