当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript isomorphic-fetch.default函数代码示例

本文整理汇总了TypeScript中isomorphic-fetch.default函数的典型用法代码示例。如果您正苦于以下问题:TypeScript default函数的具体用法?TypeScript default怎么用?TypeScript default使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了default函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: issueRequest

function issueRequest(baseUrl: string, req: string | Request, init?: RequestInit): Promise<any> {
    // Resolve relative URLs
    if (baseUrl) {
        if (req instanceof Request) {
            const reqAsRequest = req as Request;
            reqAsRequest.url = url.resolve(baseUrl, reqAsRequest.url);
        } else {
            req = url.resolve(baseUrl, req as string);
        }
    } else if (!isBrowser) {
        // TODO: Consider only throwing if it's a relative URL, since absolute ones would work fine
        throw new Error(`
            When running outside the browser (e.g., in Node.js), you must specify a base URL
            before invoking domain-task's 'fetch' wrapper.
            Example:
                import { baseUrl } from 'domain-task/fetch';
                baseUrl('http://example.com'); // Relative URLs will be resolved against this
        `);
    }

    // Currently, some part of ASP.NET (perhaps just Kestrel on Mac - unconfirmed) doesn't complete
    // its responses if we send 'Connection: close', which is the default. So if no 'Connection' header
    // has been specified explicitly, use 'Connection: keep-alive'.
    init = init || {};
    init.headers = init.headers || {};
    if (!init.headers['Connection']) {
        init.headers['Connection'] = 'keep-alive';
    }

    return isomorphicFetch(req, init);
}
开发者ID:An0564,项目名称:JavaScriptServices,代码行数:31,代码来源:fetch.ts

示例2: fetch

  get<T>(key: string): Promise<T>{
    const url = this.getUrlForKey(key);
    const promise = this.requestInit ? fetch(url, this.requestInit()) : fetch(url);
    return promise.then(r => {
      if (r.ok){
        return r.json<T>()
      }

      return Promise.reject("Unable to fetch");
    })
  }
开发者ID:Rocketmakers,项目名称:rokot-config,代码行数:11,代码来源:fetchConfigProvider.ts

示例3: fetchWithLogin

async function fetchWithLogin(url: string, options?) {
    try {
        const token = localStorage.getItem('token');
        if (token) {
            return await fetch(url, Object.assign({}, options, {headers: Object.assign({}, options && options.headers || {}, {Authorization: `Bearer ${token}`})}));
        } else {
            return await fetch(url, Object.assign({}, options, isBundle ? {credentials: 'include'} : {}));
        }
    } catch (e) {
        throw new Error(e.message);
    }
}
开发者ID:get-focus,项目名称:focus-help-center,代码行数:12,代码来源:api.ts

示例4: it

    it('should create a root user', async () => {
      const userExecutor = kiln.build('user', sqlExtension)
      state.rootUser = await userExecutor.create({
        firstName: 'Root',
        lastName: 'User',
        accountId: state.account.id,
        role: 'admin',
        email: 'root@example.com',
        password: 'password12',
      })

      await sqlExtension.sequelize.query(
        `UPDATE example_users SET role = 'root' WHERE id = ${state.rootUser.id}`,
      )

      Object.assign(state.rootUser, {
        role: 'root',
        createdAt: state.rootUser.createdAt.toJSON(),
        updatedAt: state.rootUser.updatedAt.toJSON(),
      })

      const login = {grant_type: 'password', username: 'root@example.com', password: 'password12'}
      const loginResponse = await fetch(`${state.baseURL}/v1/oauth/token`, {
        method: 'POST',
        body: JSON.stringify(login),
        headers: {'content-type': 'application/json'},
      })

      const token = (await loginResponse.json()).access_token
      state.rootCookie = `token=${token}`
    })
开发者ID:patrickhulce,项目名称:klay,代码行数:31,代码来源:create-account.test.ts

示例5: issueRequest

function issueRequest(baseUrl: string, req: string | Request, init?: RequestInit): Promise<any> {
    const reqUrl = (req instanceof Request) ? req.url : req;
    const isRelativeUrl = reqUrl && !isAbsoluteUrl(reqUrl);

    // Resolve relative URLs
    if (baseUrl) {
        if (req instanceof Request) {
            const reqAsRequest = req as Request;
            (reqAsRequest as any).url = url.resolve(baseUrl, reqAsRequest.url);
        } else {
            req = url.resolve(baseUrl, req as string);
        }
    } else if (isNode) {
        // TODO: Consider only throwing if it's a relative URL, since absolute ones would work fine
        throw new Error(`
            When running outside the browser (e.g., in Node.js), you must specify a base URL
            before invoking domain-task's 'fetch' wrapper.
            Example:
                import { baseUrl } from 'domain-task/fetch';
                baseUrl('http://example.com'); // Relative URLs will be resolved against this
        `);
    }

    init = applyHttpsAgentPolicy(init, isRelativeUrl, baseUrl);
    return isomorphicFetch(req, init);
}
开发者ID:aspnet,项目名称:Home,代码行数:26,代码来源:fetch.ts

示例6: it

 it('should return only published articles when not connected', mochaAsync(async () => {
     const articles = await(await fetch('http://localhost:1337/api/article')).json<IArticle[]>();
     chai.expect(articles).to.be.a('array');
     chai.expect(articles).to.have.length(2);
     chai.expect(articles[0].title).to.equal(article1.title);
     chai.expect(articles[1].description).to.equal(article2.description);
 }));
开发者ID:get-focus,项目名称:focus-help-center,代码行数:7,代码来源:article-tests.ts

示例7: getConfig

export async function getConfig() {
    const response = await fetch(`${appUrl}/config`);
    const config = await response.json();
    backOfficeUrl = config.backOfficeUrl;
    appUrl = config.appUrl;
    return true;
}
开发者ID:get-focus,项目名称:focus-help-center,代码行数:7,代码来源:config.ts

示例8: fetchJson

async function fetchJson(url, args) {
  const { headers = {} } = args;
  headers['Content-Type'] = 'application/json';

  let response;
  try {
    response = await fetch(url, { ...args, headers });
  } catch (networkError) {
    // e.g. server unreachable
    throw ({
      error: `Network error: ${networkError.toString()}`,
    });
  }

  let body;
  try {
    body = await response.json();
  } catch (convertError) {
    throw ({
      error: `Response was not JSON: ${convertError.toString()}`,
    });
  }

  if (response.ok) {
    // HTTP 2xx
    return body;
  } else {
    // HTTP 4xx, 5xx (e.g. malformed JSON request)
    throw body;
  }
}
开发者ID:integer32llc,项目名称:rust-playground,代码行数:31,代码来源:actions.ts

示例9: fetch

    private queryServer<T>(method:string, path:string, data?:any):Promise<T> {
        let fullpath = this.constructPath(path);
        let headers = new Headers();

        if (this._config.token) {
            headers.set("Authorization", this._config.token);
        }
        if (data) {
            headers.set("Content-Type", "application/json");
        }

        var requestConfig:RequestInit = {
            method: method,
            mode: "cors",
            headers: headers
        };
        if (data) {
            requestConfig.body = JSON.stringify(data);
        }

        return fetch(fullpath, requestConfig).then(response => {
            if (!response.ok) {
                if (response.status == 401 || response.status == 403) {
                    throw new AuthenticationError();
                }
                throw new StatusError(response.status, response.statusText);
            }
            return response.json<T>();
        });
    }
开发者ID:asarium,项目名称:fs2netd-frontend,代码行数:30,代码来源:ApiClient.ts

示例10: initPostToCategory

function initPostToCategory(categorySlug, callback) {
  "use strict";
  // Fetch post title for each category
  fetch(`https://public-api.wordpress.com/rest/v1.1/sites/sscodex.wordpress.com/posts/?category=${categorySlug}&order=ASC&fields=ID,title,categories,slug&number=100`)
    .then((response) => response.json())
    .then((json) => {
      const {posts = []} = json;
      if (!posts.length) {
        return;
      }

      const filteredPost = posts.filter((post, key) => {
        const {categories = []} = post;
        let contained = false;

        Object.keys(categories).forEach(function(key) {
          if (categories[key].slug === categorySlug) {
            contained = true;
          }
        });

        if (contained) {
          return true;
        } else {
          return false;
        }
      });

      callback(filteredPost);
    });
}
开发者ID:SoftwareSeniPT,项目名称:sscodex-beta,代码行数:31,代码来源:sidebar.act.ts


注:本文中的isomorphic-fetch.default函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。