【问题标题】:Superagent with absolute url prefix具有绝对 url 前缀的超级代理
【发布时间】:2017-07-16 23:53:44
【问题描述】:

我注意到,每次我想用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和agent。

【问题讨论】:

    标签: node.js absolute-path superagent


    【解决方案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))
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2017-07-17
        • 1970-01-01
        • 2012-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-05
        • 2019-06-06
        • 2012-03-24
        相关资源
        最近更新 更多