Home > Blockchain >  How to update content in dynamic URLs in Express?
How to update content in dynamic URLs in Express?

Time:03-25

Below have I created 3 URL's from the fn array. In real life, this would be approx 200 different filenames.

After I have created them, would I like to be able to update the content of the URL's to be either 1 or 0.

With the below PoC, the content doesn't change.

Question

Does anyone know how I can change the content of the URL's on-the-fly?

const express = require('express');
const app = express();

const fn = ['filename1', 'filename2', 'filename3'];

for (const e of fn) {
  app.get(`/${e}`, (req, res) => {
    res.send(e);
  });
};

app.get(`/filename1`, (req, res) => {
  res.send('test');
});

const port = 1900;
app.listen(port, () => {
  console.log(`http://localhost:${port}/`);
});

CodePudding user response:

You can create one wildcard route listener and add your logic inside of it

const express = require('express');
const app = express();

const fn = ['filename1', 'filename2', 'filename3'];

app.get("/*", (req, res) => {
  // Do your logic inside
  if(fn.includes(req.url.replace('/',''))) res.send('ok');
  
  res.status(404);
});


const port = 1900;
app.listen(port, () => {
  console.log(`http://localhost:${port}/`);
});
  • Related