expressjs中的两个应用程序 [英] Two apps in expressjs
问题描述
您所做的应用程序
在express中是一个适用于Express自己的中间件链的函数(req,res,next)。因此,您可以使用 app.use
将匹配前导路径片段的请求发送到其他位置定义的应用程序。
文档: http://expressjs.com/api.html#app.use
$ npm install express
//mobile.js
var app = require('express' )();
app.get('/',function(req,res){
res.send('Mobile Route')
});
module.exports = app;
//desktopApp.js
var http = require('http');
var express = require('express');
var desktopApp = express();
var mobileApp = require('./ mobile.js');
desktopApp.use('/ mobile',mobileApp)
desktopApp.use(desktopApp.router);
desktopApp.use(express.errorHandler());
desktopApp.get('/',function(req,res){
res.send('Desktop Route')
});
desktopApp.get('/ mobile',function(req,res){
//因为Express尊重你设置中间件链的顺序,
// mobileApp`/ mobile`路由首先发送响应或next()
res.send('Inaccessible Desktop Route')
});
desktopApp.get('/ mobile / foobar',function(req,res){
//当mobileApp找不到匹配此路径的任何合适路由时,它会给
// up,desktopApp继续将请求传递给中间件堆栈
//最终匹配此路由,发送响应
res.send('Desktop Route')
});
http.createServer(desktopApp).listen(3000,function(){
console.log('Listening on 3000');
});
//结果
$ curl localhost:3000 /
桌面路由
$ curl localhost:3000 / mobile /
移动路由
I am building an app with express js which will have different clients like web and mobile. I didnt want to use one app for both as some middleware would be additional burden. For say like session middleware. So is it possible for one project to have two apps. And how would it work?
The app
object that you make in express is a function(req,res,next) that is suitable for Express's own middleware chains. So you can use app.use
to send requests matching a leading path fragment to an app defined elsewhere.
Docs: http://expressjs.com/api.html#app.use
$ npm install express
//mobile.js
var app = require('express')();
app.get('/', function(req, res){
res.send('Mobile Route')
});
module.exports = app;
//desktopApp.js
var http = require('http');
var express = require('express');
var desktopApp = express();
var mobileApp = require('./mobile.js');
desktopApp.use('/mobile', mobileApp)
desktopApp.use(desktopApp.router);
desktopApp.use(express.errorHandler());
desktopApp.get('/', function(req, res){
res.send('Desktop Route')
});
desktopApp.get('/mobile', function(req, res){
// Because Express respects the order that you set up the middleware chain,
// the mobileApp `/mobile` route gets first dibs to send a response or next()
res.send('Inaccessible Desktop Route')
});
desktopApp.get('/mobile/foobar', function(req, res){
// When mobileApp can't find any suitable route matching this path, it gives
// up, and desktopApp continues to pass the request down the middleware stack.
// It ends up matching this route, where we send a response
res.send('Desktop Route')
});
http.createServer(desktopApp).listen(3000, function(){
console.log('Listening on 3000');
});
// Results
$ curl localhost:3000/
Desktop Route
$ curl localhost:3000/mobile/
Mobile Route
这篇关于expressjs中的两个应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!