is an unopinionated Node.js framework. LoopBackREST API can be mounted to an Express application and be used as middleware.This way the user can mix and match features from both frameworks to suit theirneeds.
Note:
If you want to use LoopBack as the host instead and mount your Expressapplication on a LoopBack 4 application, seeMounting an Express Router.
This tutorial assumes familiarity with scaffolding a LoopBack 4 application,, DataSources
,, and Controllers
. To seehow they’re used in a LoopBack application, please see the.
If you’d like to see the final results of this tutorial as an exampleapplication, follow these steps:
- Run the
lb4 example
command to select and clone the express-compositionrepository:
- Switch to the directory.
cd loopback4-example-express-composition
- Finally, start the application!
$ npm start
Server is running at http://127.0.0.1:3000
Run lb4 app note
to scaffold your application and fill out the followingprompts as follows:
$ lb4 app note
? Project description: An application for recording notes.
? Project root directory: (note)
? Application class name: (NoteApplication)
◉ Enable eslint: add a linter with pre-configured lint rules
◉ Enable prettier: install prettier to format code conforming to rules
◉ Enable mocha: install mocha to run tests
◉ Enable loopbackBuild: use @loopback/build helpers (e.g. lb-eslint)
◉ Enable vscode: add VSCode config files
❯◯ Enable docker: include Dockerfile and .dockerignore
◉ Enable repositories: include repository imports and RepositoryMixin
◉ Enable services: include service-proxy imports and ServiceMixin
# npm will install dependencies now
Application note was created in note.
Inside the project folder, run lb4 model
to create the Note
model withEntity
model base class. Add an id
property with type number
, a requiredtitle
property with type string
, and a content
property of type string
.
Now, let’s create a simple in-memory datasource by running thelb4 datasource ds
command and the following full path to file:./data/ds.json
.
Similar to the Todo
example, let’s create the ds.json
by creating a datafolder at the application’s root.
$ mkdir data
$ touch data/ds.json
Then copy and paste the following into the ds.json
file:
To complete the Note
application, create a controller using thelb4 controller note
command, with the REST Controller with CRUD functions
type, model, and NoteRepository
repository. The id
’s type will benumber
and base HTTP path name is the default /notes
.
Let’s start by installing dependencies for the express
module:
npm install --save express
npm install --save-dev @types/express
Create a new file src/server.ts to create your Express class:
src/server.ts
import * as express from 'express';
export class ExpressServer {
constructor() {}
}
Create two properties, the Express application instance and LoopBack applicationinstance:
import {ApplicationConfig} from '@loopback/core';
import * as express from 'express';
export class ExpressServer {
private app: express.Application;
private lbApp: NoteApplication;
constructor(options: ApplicationConfig = {}) {
this.app = express();
this.lbApp = new NoteApplication(options);
}
}
Now, inside the constructor, we’re going to add the basepath and expose thefront-end assets via Express:
this.app.use('/api', this.lbApp.requestHandler);
Let’s also modify public/index.html to update the base path:
public/index.html
Then, we can add some custom Express routes, as follows:
import {Request, Response} from 'express';
import * as path from 'path';
export class ExpressServer {
private app: express.Application;
private lbApp: NoteApplication;
constructor(options: ApplicationConfig = {}) {
// earlier code
// Custom Express routes
this.app.get('/', function(_req: Request, res: Response) {
res.sendFile(path.resolve('public/express.html'));
});
this.app.get('/hello', function(_req: Request, res: Response) {
res.send('Hello world!');
});
}
}
And add thepublic/express.htmlfile to your project.
npm install --save p-event
Finally, we can add functions to boot the application and start theExpress application:
import pEvent from 'p-event';
export class ExpressServer {
private app: express.Application;
private lbApp: NoteApplication;
constructor(options: ApplicationConfig = {}) {
//...
}
async boot() {
await this.lbApp.boot();
}
async start() {
const port = this.lbApp.restServer.config.port || 3000;
const host = this.lbApp.restServer.config.host || '127.0.0.1';
const server = this.app.listen(port, host);
await pEvent(server, 'listening');
}
}
Now that our src/server.ts file is ready, then we can modify oursrc/index.ts file to start the application:
src/index.ts
import {ExpressServer} from './server';
import {ApplicationConfig} from '@loopback/core';
export {ExpressServer, NoteApplication};
export async function main(options: ApplicationConfig = {}) {
const server = new ExpressServer(options);
await server.boot();
await server.start();
console.log('Server is running at http://127.0.0.1:3000');
}
Now let’s start the application and visit :
If we go to the Explorer, we can makerequests for our LoopBack application. Notice how the server is.
To view our custom /hello
Express route, go to http://127.0.0.1:3000/helloand you should see ‘Hello world!’.
To serve static files in your application, add the following to the end of yourconstructor:
src/server.ts
export class ExpressServer {
private app: express.Application;
private lbApp: NoteApplication;
constructor(options: ApplicationConfig = {}) {
// earlier code
// Serve static files in the public folder
this.app.use(express.static('public'));
}
// other functions
Now, you can load any static files in the public/ folder. For example, addthe followingfile to your project, run npm start
again, and visithttp://127.0.0.1:3000/notes.html. You can now see a static file that willdisplay your Notes in a table format. For more information, please visit.
Congratulations, you just mounted LoopBack 4 REST API onto a simple Expressapplication.