kbsbng
kbsbng

Reputation: 2361

Request to the an endpoint on the same server in express js

While handling a request on a express js server, I want to call an endpoint on the same server in order to fill part of the response. Is there a way I can call an endpoint on the same server?

Something like:

app.handle("/abc", {
    headers: {
    },
    params: {
    },
    type: "GET"
}, function (err, resp) {});

Upvotes: 4

Views: 6292

Answers (1)

esp
esp

Reputation: 7687

You can do it with supertest library (using it in the application, not in the test):

var handleRequest = require('supertest');

var request = handleRequest(app)[params.method](params.path)
.set('Accept', 'application/json')
.set(params.headers);

if (body) request.send(params.body);

request.end(function (err, resp) {
  console.log(resp.body);
});

where params is an object with the parameters of the request you want to process, params.method should be lowercase HTTP verb.

Alternatively you can use mocks for request and response objects and call:

app.handle(reqMock, resMock, cb)

Upvotes: 1

Related Questions