我在后端有快递,在前端有反应,但我也有管理页面在处理哈巴狗模板,我如何在一个域上运行它



我在后端有快递,在前端有反应.js但我也有带有 pug 视图引擎的管理页面,在快速路由上工作,我如何在一个域中使用这些

Expressjs以一种非常好的方式可以组合。您可以拥有一个顶级快递应用程序,该应用程序路由到子快递应用程序并提供您的个人服务。

假设你想从www.example.com提供你的反应前端,从www.example.com/admin提供你的管理员(哈巴狗视图),你还想有一个 api 在 www.example.com/api 时为 react 前端提供服务。

您可能想要一些类似于以下代码示例的内容,该示例演示了快速应用程序的组成。我没有运行代码,但它应该足以让你开始。

// This parent app acts as a parent layer and router
// for all your "sub apps". Any middleware you apply
// to this express app will apply to *all your other
// sub-apps*.
const parentApp = express();
// We now create another express instance, this will
// house the API. It can be in another file and you
// could require in something like "require('api');"
// instead but for brevity we'll keep it all in one
// file.
const apiApp = express();
apiApp.get('/info', (req, res, next) => {
console.log('/info');
return res.sendStatus(200);
});
// Mount the sub app on the /api route. This means
// you can how hit 'www.example.com/api/info' and
// you'll get back a 200 status code.
parentApp.use('/api', apiApp);
// Now we setup the admin app which we'll add pug
// views into. This is an example so just pretend
// the views exist.
const adminApp = express();
adminApp.set('views', './views');
adminApp.set('view engine', 'pug');
adminApp.get('/login', (req, res, next) => {
return res.render('login', { title: 'Hey' });
});
// Mount the sub app on the /admin route. This way
// we can hit www.example.com/admin/login to get
// our login page rendered.
parentApp.use('/admin', adminApp);
// Now we create and mount the frontend app that
// serves our fully built react app. You could do
// this with nginx instead but you wanted to do
// it with express so lets do it that way.
const frontendApp = express();
frontendApp.use(express.static('/frontend));
parentApp.use('/', frontendApp);

如果您不想为自己创建一个顶级快速应用程序(从而创建一个整体应用程序),那么我建议您查看nginx文档或您使用的HTTP服务器的文档。您应该能够将特定端点的请求定向到在不同端口上运行的不同节点应用程序。然后,静态文件可以由 HTTP 服务器本机提供。这绝对是一种更有效和优雅的方法,但既然你问了快递,我想主要展示这种方法。

最新更新