description | full_title |
---|---|
This tutorial shows how to use and extend the Express server. |
Express Tutorial |
This tutorial shows how to use and extend the Express server.
NOTE: A body-parser middleware is used by default to decode both JSON and urlencoded data.
You can retrieve the Express server and all other related instances via the core
class injected into all methods.
app
- The Expressexpress()
instancesession
- The Express sessionws
- The Express WebSockethttpServer
- Thehttp.Server
instance
You can use the provided methods to set up routes from your Applications and Service Providers:
[info] If you're adding routes in your service provider using this API, use the
start()
method in your provider.
[info] Note that the last argument int
routeAuthenticated
(strict group check argument) defaults toauth.requireAllGroups
configuration option.
const {route, routeAuthenticated} = core.make('osjs/express');
const respond = (req, res) => res.json({result: 'pong'});
// Regular route
route('GET', '/ping', respond);
// Same as above, except requires user to be authenticated
routeAuthenticated('GET', '/ping', respond);
// Same as above, but also requires user to belong to *some* given groups (see note above)
routeAuthenticated('GET', '/ping', respond, ['admin']);
// Same as above, but also requires user to belong to *all* given groups
routeAuthenticated('GET', '/ping', respond, ['admin'], true);
To inject middleware into the route handler (route()
and routeAuthenticated()
), use the following service:
const {middleware} = core.make('osjs/express');
middleware(true, (req, res, next) => {}); // routeAuthenticated()
middleware(false, (req, res, next) => {}); // route()
You can also directly hook into the Express instance.
In your src/server/index.js
file:
const osjs = new Core(config, {});
osjs.on('init', () => osjs.app.get('/ping', (req, res) => {}));
class ServiceProvider {
start() {
this.core.app.get('/ping', (req, res) => {});
}
}
To add middleware or other extensions to Express, you can add this in a couple of ways:
In your src/server/index.js
file:
const something = require('library');
const osjs = new Core(config, {});
osjs.app.use(something);
const something = require('library');
class ServiceProvider {
constructor(core, options) {
this.core = core;
this.options = options;
this.core.app.use(something)
}
}
You can access the session via req.session
.
See Application tutorial on how to attach your applications to the server.