I created 4 serverless routes
I included them in the api/now.json file like this:
{"src": "/api/list", "dest": "./list.js", "methods": ["GET"]},
{"src": "/api/add", "dest": "./add.js", "methods": ["POST"]},
{"src": "/api/update/*", "dest": "./update.js", "methods": ["PUT"]},
{"src": "/api/remove/*", "dest": "./remove.js", "methods": ["DELETE"]}
The /api/list and /api/add routes which don't use parameters are working, but /api/update and /api/remove aren't working, because I probably didn't use the regex on the api path in the above quoted now.json file correctly.
The handler for the router looks like this (only the relevant path)
app.put('/api/update/:id', (req, res) => {
...
});
module.exports = app;
The src
is the incoming request path that you want to match, and dest
is the file that should execute.
That means you don't need any routes for your first two because visiting /api/list
will execute the function in your file /api/list.js
and /api/add
will execute /api/add.js
.
You can use rewrites in a now.json
file to define routes similar to express patterns:
{
"rewrites": [
{ "source": "/update/:id", "destination": "/api/update" },
{ "source": "/remove/:id", "destination": "/api/remove" }
]
}
An example function in /api/remove.js
would look like:
module.exports = (req, res) => {
const { id } = req.query;
res.send('Removing ID ' + id);
});
Alternatively, you could name your file /api/remove/[id].js
and then you wouldn't need to define rewrites
configuration at all. This is called Path Segments.