简体   繁体   中英

Express.js | Node.js - Can I use a resource in a different resource?

When I have two "get" resources in my node.js/express.js program, can I use the first resource in the second resource?

Example:

var express = require('express');

var app = express();

app.get('/resource1', function (req, res) {
    res.send("Hello");
}

app.get('/resource2', function (req, res) {

    // Can I use the response from resource1 here?

}

If so, how can I do that?

You can try to do 2 things:

  1. you can make an http request from resource2 to resource1 and get the response from there.

  2. The better solution in my eyes is to put resource1 logics in a "Business logics" function and call this function from the resource2 endpoint.

You can also call the actual request function of resource1 if you re-write the code to:

app.get('/resource1', resource1Func);

function resource1Func(req, res)
{
    res.send("Hello");
}

app.get('/resource2', function (req, res) {
    resource1Func(res, res);
    //some other logics
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM