Superagent有绝对的url前缀

时间:2017-02-26 10:57:07

标签: node.js absolute-path superagent

我注意到每次想要使用superagent运行节点测试时,我都会写http://localhost

import superagent from 'superagent';

const request = superagent.agent();
request
  .get('http://localhost/whatever')
  .end((err, res) => { ... });

有没有办法避开localhost部分?

就我而言,我要避免将请求硬编码到主机:

const baseUrl = 'http://localhost:3030';

request
  .get(`${baseUrl}/whatever`)

但我每次都必须随身携带baseUrl

2 个答案:

答案 0 :(得分:1)

虽然最近没有像superagent-absolute那样更新软件包,但是superagent-prefix正式是recommended,并且在2020年采用率最高。

It is such a simple package,我不会担心缺少更新。

用法示例:

import superagent from "superagent"
import prefix from "superagent-prefix"

const baseURL = "https://foo.bar/api/"
const client = superagent.use(prefix(baseURL))

答案 1 :(得分:0)

TL; DR: superagent-absolute正是如此。

<强>详细说明:

您可以在superagent之上创建一个抽象层。

function superagentAbsolute(agent) {
  return baseUrl => ({
    get: url => url.startsWith('/') ? agent.get(baseUrl + url) : agent.get(url),
  });
}

⬑当使用起始agent.get

调用时,它会覆盖/
global.request = superagentAbsolute(agent)('http://localhost:3030');

现在你需要做同样的事情:DELETE,HEAD,PATCH,POST和PUT。

https://github.com/zurfyx/superagent-absolute/blob/master/index.js

const OVERRIDE = 'delete,get,head,patch,post,put'.split(',');
const superagentAbsolute = agent => baseUrl => (
  new Proxy(agent, {
    get(target, propertyName) {
      return (...params) => {
        if (OVERRIDE.indexOf(propertyName) !== -1 
            && params.length > 0 
            && typeof params[0] === 'string' 
            && params[0].startsWith('/')) {
          const absoluteUrl = baseUrl + params[0];
          return target[propertyName](absoluteUrl, ...params.slice(1));
        }
        return target[propertyName](...params);
      };
    },
  })
);

或者您只需使用superagent-absolute

const superagent = require('superagent');
const superagentAbsolute = require('superagent-absolute');

const agent = superagent.agent();
const request = superagentAbsolute(agent)('http://localhost:3030');

it('should should display "It works!"', (done) => {
  request
    .get('/') // Requests "http://localhost:3030/".
    .end((err, res) => {
      expect(res.status).to.equal(200);
      expect(res.body).to.eql({ msg: 'It works!' });
      done();
    });
});