當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。