Section 4: "JetNode.js" - Building Web Services with Express and the IBM i Toolkit
Let's build a tiny Express app so the moving parts make sense before the real thing.
// app.js
const express = require('express');
const app = express();
// Middleware: parse JSON request bodies
app.use(express.json());
// Middleware: a very simple request logger
app.use((req, res, next) => {
console.log(new Date().toISOString(), req.method, req.url);
next(); // pass control to the next middleware/route
});
// Route: GET /
app.get('/', (req, res) => {
res.send('Hello from Express on IBM i!');
});
// Route with a URL parameter: GET /hello/Nick
app.get('/hello/:name', (req, res) => {
res.json({ message: `Hello, ${req.params.name}!` });
});
// Route that reads a JSON body: POST /echo
app.post('/echo', (req, res) => {
res.status(201).json({ youSent: req.body });
});
// 404 handler (no route matched)
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
// Error handler (4 arguments = Express treats it as error middleware)
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
const express = require('express');
const app = express();
// Middleware: parse JSON request bodies
app.use(express.json());
// Middleware: a very simple request logger
app.use((req, res, next) => {
console.log(new Date().toISOString(), req.method, req.url);
next(); // pass control to the next middleware/route
});
// Route: GET /
app.get('/', (req, res) => {
res.send('Hello from Express on IBM i!');
});
// Route with a URL parameter: GET /hello/Nick
app.get('/hello/:name', (req, res) => {
res.json({ message: `Hello, ${req.params.name}!` });
});
// Route that reads a JSON body: POST /echo
app.post('/echo', (req, res) => {
res.status(201).json({ youSent: req.body });
});
// 404 handler (no route matched)
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
// Error handler (4 arguments = Express treats it as error middleware)
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
Run it:
node app.js
And test from another SSH session (or your PC):
curl http://myibmi:3000/
curl http://myibmi:3000/hello/Nick
curl -X POST http://myibmi:3000/echo -H 'Content-Type: application/json' -d '{"cheese":"cheddar"}'
curl http://myibmi:3000/hello/Nick
curl -X POST http://myibmi:3000/echo -H 'Content-Type: application/json' -d '{"cheese":"cheddar"}'
Adding Db2 for i
Here's a route that runs SQL. Note the connection pool - created once at start-up and shared by every request:
// db-demo.js
const express = require('express');
const odbc = require('odbc');
async function start() {
const pool = await odbc.pool(
`DSN=*LOCAL;UID=${process.env.DB_USER};PWD=${process.env.DB_PASS}`
);
const app = express();
app.get('/sysvals/date', async (req, res, next) => {
try {
const rows = await pool.query(
'SELECT CURRENT_DATE AS TODAY, CURRENT_TIME AS NOW FROM SYSIBM.SYSDUMMY1'
);
res.json(rows[0]);
} catch (err) {
next(err); // hand it to the error handler
}
});
app.listen(3000, () => console.log('db-demo on 3000'));
}
start().catch(err => { console.error(err); process.exit(1); });
const express = require('express');
const odbc = require('odbc');
async function start() {
const pool = await odbc.pool(
`DSN=*LOCAL;UID=${process.env.DB_USER};PWD=${process.env.DB_PASS}`
);
const app = express();
app.get('/sysvals/date', async (req, res, next) => {
try {
const rows = await pool.query(
'SELECT CURRENT_DATE AS TODAY, CURRENT_TIME AS NOW FROM SYSIBM.SYSDUMMY1'
);
res.json(rows[0]);
} catch (err) {
next(err); // hand it to the error handler
}
});
app.listen(3000, () => console.log('db-demo on 3000'));
}
start().catch(err => { console.error(err); process.exit(1); });
That try / catch / next(err) pattern is the Express 4 way to get errors from async routes into the error handler. Remember it - we'll use it in every CRUD route.
