且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Express JS中请求到同一服务器上的端点

更新时间:2023-11-22 17:31:58

您可以使用 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)