Things I learned:
1. The characters ?
, +
, *
, and ()
are subsets of their regular expression counterparts. The hyphen (-
) and the dot (.
) are interpreted literally by string-based paths.
2. res.send([body]) can sends the HTTP response. The body parameter can be a Buffer object, a String, an object, or an Array, but not a Number object.
So, I made a basic server can do subtraction.
Code:
const express = require('express');
const app = express();
const port = 3000;
app.get(‘/’, (req, res) => res.send(‘Subtraction with Route’));
app.get(‘/:a-:b’, function (req, res) {
var sub = parseInt(req.params.a,10) – parseInt(req.params.b,10);
res.send(sub.toString());
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Here is my question: How to detect plus size (+) in route path with Express? Finally, I ended with the following solution:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Subtraction with Route'));
app.get('/:a-:b', function (req, res) {
var sub = parseInt(req.params.a,10) - parseInt(req.params.b,10);
res.send(sub.toString());
});
// I used "\\" to escape regex plus sign.
app.get('/:a\\+:b', function (req, res) {
var sum = parseInt(req.params.a,10) + parseInt(req.params.b,10);
res.send(sum.toString());
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Resource