我们可以使用dredd工具连接到公共api端点而不是本地主机吗?

时间:2018-04-19 13:44:29

标签: dredd

我尝试使用公共端点(例如:api.openweathermap.org/data/2.5/weather?lat = 35& lon = 139)而不是本地主机,同时配置dredd并运行命令来运行该工具但是我无法通过dredd连接到终点。它抛出错误:getaddrINFO EAI_AGAIN。 但是当我尝试使用post man连接到端点时。我能够成功连接

1 个答案:

答案 0 :(得分:1)

调用本地或远程端点没有区别。

某些远程端点具有某种授权要求。

这是Dredd调用外部端点的示例:

dredd.yml配置文件片段

...
blueprint: doc/api.md
# endpoint: 'http://api-srv:5000'
endpoint: https://private-da275-notes69.apiary-mock.com

如您所见,唯一的变化是Dredd配置文件上的端点(使用Dredd init创建)。

但是,正如我提到的,有时您需要通过标头或查询字符串参数提供授权。

Dreed具有挂钩,可让您在每次交易前更改事物,例如:

您想在执行请求之前在每个URL中添加apikey参数。这段代码可以解决这个问题。

hook.js

// Writing Dredd Hooks In Node.js
// Ref: http://dredd.org/en/latest/hooks-nodejs.html

var hooks = require('hooks');

hooks.beforeEach(function(transaction) {
  hooks.log('before each');
  // add query parameter to each transaction here
  let paramToAdd = 'api-key=23456';
  if (transaction.fullPath.indexOf('?') > -1)
    transaction.fullPath += '&' + paramToAdd;
  else
    transaction.fullPath += '?' + paramToAdd;

  hooks.log('before each fullpath: ' + transaction.fullPath);
});

Github gist处的代码

将此hook文件保存在项目中的任何位置,然后运行Dredd传递挂钩文件。

dredd --hookfiles=./hoock.js

就是这样,执行后,日志将显示请求中使用的实际URL。

info: Configuration './dredd.yml' found, ignoring other arguments.
2018-06-25T16:57:13.243Z - info: Beginning Dredd testing...
2018-06-25T16:57:13.249Z - info: Found Hookfiles: 0=/api/scripts/dredd-hoock.js
2018-06-25T16:57:13.263Z - hook: before each
2018-06-25T16:57:13.264Z - hook: before each fullpath: /notes?api-key=23456
"/notes?api-key=23456"
2018-06-25T16:57:16.095Z - pass: GET (200) /notes duration: 2829ms
2018-06-25T16:57:16.096Z - hook: before each
2018-06-25T16:57:16.096Z - hook: before each fullpath: /notes?api-key=23456
"/notes?api-key=23456"
2018-06-25T16:57:16.788Z - pass: POST (201) /notes duration: 691ms
2018-06-25T16:57:16.788Z - hook: before each
2018-06-25T16:57:16.789Z - hook: before each fullpath: /notes/abcd1234?api-key=23456
"/notes/abcd1234?api-key=23456"
2018-06-25T16:57:17.113Z - pass: GET (200) /notes/abcd1234 duration: 323ms
2018-06-25T16:57:17.114Z - hook: before each
2018-06-25T16:57:17.114Z - hook: before each fullpath: /notes/abcd1234?api-key=23456
"/notes/abcd1234?api-key=23456"
2018-06-25T16:57:17.353Z - pass: DELETE (204) /notes/abcd1234 duration: 238ms
2018-06-25T16:57:17.354Z - hook: before each
2018-06-25T16:57:17.354Z - hook: before each fullpath: /notes/abcd1234?api-key=23456
"/notes/abcd1234?api-key=23456"
2018-06-25T16:57:17.614Z - pass: PUT (200) /notes/abcd1234 duration: 259ms
2018-06-25T16:57:17.615Z - complete: 5 passing, 0 failing, 0 errors, 0 skipped, 5 total
2018-06-25T16:57:17.616Z - complete: Tests took 4372ms