首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我有快递在后端和反应在前端,但我也有管理页面上的pug模板工作,我怎么能在一个域上运行它

问我有快递在后端和反应在前端,但我也有管理页面上的pug模板工作,我怎么能在一个域上运行它
EN

Stack Overflow用户
提问于 2019-04-03 21:38:53
回答 1查看 160关注 0票数 0

我有快递在后端和react.js在前端,但我也有管理页面与pug视图引擎,在快递路线上的工作,我如何使用这些在一个领域

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-03 22:07:05

Expressjs以一种非常好的方式进行组合。你可以有一个顶级的express应用程序,它可以路由到子express应用程序并为您的个人服务提供服务。

假设你想从www.example.com为你的react前端提供服务,从www.example.com/admin为你的管理(pug视图)提供服务,并且你还想在www.example.com/api`上有一个服务于react前端的api。

您可能需要类似以下代码示例的内容,该示例演示了express应用程序的组成。我还没有运行代码,但它应该足以让您运行起来。

代码语言:javascript
复制
// 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);

如果你不想创建一个顶级的express应用程序(也就是说创建了一个庞大的应用程序),那么我建议你查看nginx文档,或者你所使用的HTTP服务器的文档。您应该能够将针对特定端点的请求定向到在不同端口上运行的不同节点应用程序。然后,静态文件可以由您的HTTP服务器提供本机服务。这绝对是一种更高效、更优雅的方法,但既然你问到了express,我想主要展示一下这种方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55496603

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档