在Express JS中请求到同一服务器上的端点 [英] Request to the an endpoint on the same server in express js

查看:71
本文介绍了在Express JS中请求到同一服务器上的端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在快速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?

类似的东西:

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

推荐答案

您可以使用 supertest 库(在应用程序中使用它,而不是在测试中使用):

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);
});

其中params是具有要处理的请求参数的对象,params.method应该是小写的HTTP动词.

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)

这篇关于在Express JS中请求到同一服务器上的端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆