Brent Deighton
Brent Deighton

Reputation: 23

Can you call app.get() from a function within nodeJS (Express)

So im currently doing a little side project, and was playing around with nodeJS, was wondering whether you could call a function from within a HTTP post method and then that function calls a get request.

app.post('/otherEndpoint', (req,res) => {
    var title = JSON.stringify(req.body);
    myFunction(title);

});


function myFunction(title){

    app.get(`/someEndpoint${title}`, (req,res) => {
      console.log(res);
});
}

Upvotes: 1

Views: 1993

Answers (2)

Mouradif
Mouradif

Reputation: 2704

Edit: Full demo walkthrough

Install dependencies

$ yarn add express body-parser

index.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.post('/create', (req,res) => {
  var title = req.body.title;
  myFunction(title);
  res.end('ok');
});


function myFunction(title){

  app.get(`/SE${title}`, (req,res) => {
    res.end(title);
  });
  console.log(`created route SE${title}`);
}

app.listen(3000);

Now run your script:

$ node index

And in another terminal, let's try it:

let's try to /GET SEyeah

$ curl localhost:3000/SEyeah
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /SEyeah</pre>
</body>
</html>

it's a 404. Now let's create it first :

$ curl -X POST -H 'Content-type: application/json' -d '{"title": "yeah"}' localhost:3000/create
ok

(at this point in the node process you should have "created route SEyeah")

Now let's try that first route again :

$ curl localhost:3000/SEyeah
yeah

Voila :)!

Original answer

Protip: when you wonder if something would work, try it. You're not going to set your computer on fire with JavaScript.

Yes that should work. If the function is declared in a different file, you can simply pass the app as a parameter :

app.post('/otherEndpoint', (req,res) => {
  var title = JSON.stringify(req.body);
  myFunction(app, title);
});


function myFunction(app, title){
  app.get(`/someEndpoint${title}`, (req,res) => {
    console.log(res);
  });
}

I have to give this disclaimer though: this sounds like an awful idea and you're probably better off doing something like this instead:

app.get(`/someEndpoint/:title`, (req,res) => {
  // Check if req.params.title is a valid title otherwise send a 404.
  res.end(req.params.title);
});

Upvotes: 0

Tyler2P
Tyler2P

Reputation: 2370

Instead of the method you provided in your question you could use a variable as cache and params.

Example:

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

let cache = {
    titles: []
}

app.post('/otherEndpoint', function(req, res) {
    var title = JSON.stringify(req.body);
    (cache.titles).push({ title, timestamp: new Date().getTime() });
});
app.get(`/someEndpoint/:title`, function(req, res) {
    let found = false;
    cache.titles.forEach(object => {
        if (object.title == req.params.title && object.timestamp > (new Date().getTime() - 10000)) { // Title is equal to the tile in the URL and the title was created less than 10 seconds ago
            res.send('title exists');
            found = true;
        }
    });
    if (!found) { // If the title was not found
        res.send('title doesn\'t exist or was creates more than 10 seconds ago');
    }
});

Upvotes: 1

Related Questions