• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test

            test('regex restriction, request body matches regex - match', async () => {
                const route = fakeServer.http
                    .post()
                    .to(path)
                    .withBodyThatMatches(lettersRegex)
                    [method]();
                const actualBody = 'abc';

                const res = await fetch(`http://localhost:${port}${path}`, {
                    method: 'POST',
                    headers: {'Content-Type': 'text/plain'},
                    body: actualBody,
                });

                expect(res.status).toEqual(defaultStatus);
                expect(fakeServer.hasMade(route.call)).toEqual(true);

                const callsMade = fakeServer.callsMade(route.call);
                expect(callsMade[0].path).toEqual(path);
                expect(callsMade[0].body).toEqual(actualBody);
            });
开发者ID:Soluto,项目名称:simple-fake-server,代码行数:21,代码来源:body-restrictions-on-route-definition-tests.ts


示例2: test

            test('route defined with path and body regex - chaining assertions, specific path and body match path and body regex - assertion success', async () => {
                const pathRegex = '/[a-zA-Z]+$';
                const actualPath = '/somePath';
                const bodyRegex = '[0-9]+$';
                const actualBody = '123';
                const route = fakeServer.http
                    .post()
                    .to(pathRegex)
                    .withBodyThatMatches(bodyRegex)
                    [method]();

                const res = await fetch(`http://localhost:${port}${actualPath}`, {
                    method: 'POST',
                    headers: {'Content-Type': 'text/plain'},
                    body: actualBody,
                });

                expect(res.status).toEqual(defaultStatus);
                expect(fakeServer.hasMade(route.call.withPath(actualPath).withBodyText(actualBody))).toEqual(true);
                expect(fakeServer.hasMade(route.call.withBodyText(actualBody).withPath(actualPath))).toEqual(true);
            });
开发者ID:Soluto,项目名称:simple-fake-server,代码行数:21,代码来源:route-matching-general-tests.ts


示例3: main

export default function main(): Promise<Counts> {
  const username = process.env.GITHUB_USERNAME;
  if (typeof username === 'undefined')
    return Promise.reject('GITHUB_USERNAME is not defined');
  const accessToken = process.env.GITHUB_ACCESS_TOKEN;
  if (typeof accessToken === 'undefined')
    return Promise.reject('GITHUB_ACCESS_TOKEN is not defined');
  const urlString = url.format({
    ...url.parse(`https://api.github.com/users/${username}`),
    query: qs.stringify({ access_token: accessToken })
  });
  return fetch(urlString, {})
    .then((response) => response.json())
    .then((json: GitHubResponse): Counts => {
      return {
        'GitHub Followers': json.followers,
        'GitHub Following': json.following,
        'GitHub Public Gists': json.public_gists,
        'GitHub Public Repos': json.public_repos
      };
    });
}
开发者ID:bouzuya,项目名称:cars-counter-github,代码行数:22,代码来源:index.ts


示例4: introspectServer

export async function introspectServer(url: string, method: string, headerStrings: string[]): Promise<string> {
    const headers: { [name: string]: string } = {};

    for (const name of Object.getOwnPropertyNames(defaultHeaders)) {
        headers[name] = defaultHeaders[name];
    }
    for (const str of headerStrings) {
        const matches = str.match(headerRegExp);
        if (matches === null) {
            return panic(`Not a valid HTTP header: "${str}"`);
        }
        headers[matches[1]] = matches[2];
    }

    let result;
    try {
        const response = await fetch(url, {
            method,
            headers: headers,
            body: JSON.stringify({ query: introspectionQuery })
        });

        result = await response.json();
    } catch (error) {
        return panic(`Error while fetching introspection query result: ${error.message}`);
    }

    if (result.errors) {
        return panic(`Errors in introspection query result: ${JSON.stringify(result.errors)}`);
    }

    const schemaData = result;
    if (!schemaData.data) {
        return panic(`No introspection query result data found, server responded with: ${JSON.stringify(result)}`);
    }

    return JSON.stringify(schemaData, null, 2);
}
开发者ID:nrkn,项目名称:quicktype,代码行数:38,代码来源:GraphQLIntrospection.ts


示例5: fetch

import fetch from 'node-fetch';

const API_ROOT = 'https://kitchen.kanttiinit.fi';

export default {
  getJson(path: string) {
    return fetch(API_ROOT + path).then(res => res.json());
  },
};
开发者ID:Kanttiinit,项目名称:kanttiinit-bot,代码行数:9,代码来源:http.ts


示例6: fetch

 return (query, variables?, operationName?) => {
   return fetch(url, {
     method: 'POST',
     headers: new Headers({
       "content-type": 'application/json',
       ...headersObj,
     }),
     body: JSON.stringify({
       operationName,
       query,
       variables,
     })
   }).then(responce => {
     if (responce.ok)
       return responce.json();
     return responce.text().then(body => {
       throw Error(`${responce.status} ${responce.statusText}\n${body}`);
     });
   });
 }
开发者ID:codeaudit,项目名称:graphql-faker,代码行数:20,代码来源:proxy.ts


示例7: getLights

export async function getLights() {
  const [body, rooms] = await Promise.all([
    fetch(`${api}/lights`).then(res => res.json()),
    findAll(),
  ]);

  let correctedBody = body;

  if (body) {
    rooms.forEach(({ roomId, lightId }) => {
      if (body.hasOwnProperty(lightId)) {
        body[lightId].roomId = roomId;
      }
    });

    correctedBody = toArray(body);
  }

  return correctedBody;
}
开发者ID:7h1b0,项目名称:Anna,代码行数:20,代码来源:hueService.ts


示例8: readAuthTimestamp

  async readAuthTimestamp(bucketAddress: string): Promise<number> {

    const authTimestampDir = this.getAuthTimestampFileDir(bucketAddress)
    
    let fetchResponse: Response
    try {
      const authNumberFileUrl = `${this.readUrlPrefix}${authTimestampDir}/${AUTH_TIMESTAMP_FILE_NAME}`
      fetchResponse = await fetch(authNumberFileUrl, {
        redirect: 'manual',
        headers: {
          'Cache-Control': 'no-cache'
        }
      })
    } catch (err) {
      // Catch any errors that may occur from network issues during `fetch` async operation.
      const errMsg = (err instanceof Error) ? err.message : err
      throw new errors.ValidationError(`Error trying to fetch bucket authentication revocation timestamp: ${errMsg}`)
    }

    if (fetchResponse.ok) {
      try {
        const authNumberText = await fetchResponse.text()
        const authNumber = parseInt(authNumberText)
        if (Number.isFinite(authNumber)) {
          return authNumber
        } else {
          throw new errors.ValidationError(`Bucket contained an invalid authentication revocation timestamp: ${authNumberText}`)
        }
      } catch (err) {
        // Catch any errors that may occur from network issues during `.text()` async operation.
        const errMsg = (err instanceof Error) ? err.message : err
        throw new errors.ValidationError(`Error trying to read fetch stream of bucket authentication revocation timestamp: ${errMsg}`)
      }
    } else if (fetchResponse.status === 404) {
      // 404 incidates no revocation file has been created.
      return 0
    } else {
      throw new errors.ValidationError(`Error trying to fetch bucket authentication revocation timestamp: server returned ${fetchResponse.status} - ${fetchResponse.statusText}`)
    }

  }
开发者ID:blockstack,项目名称:blockstack-registrar,代码行数:41,代码来源:revocations.ts


示例9: function

exports.handler = async function(event: APIGatewayProxyEvent, context: Context, callback: APIGatewayProxyCallback){

	// Try to grab data from dataservice and proxy it
	try{
		// Grabbing data from data service
		const res = await fetch(dataURL);
		const body = await res.text();

		// Returning data
		return {
			statusCode: 200,
			body,
		};
	}
	catch(e){
		return {
			statusCode: 500,
			body: "An error has occured while getting data"
		}
	}
}
开发者ID:andrewpe,项目名称:andrewpe.github.io,代码行数:21,代码来源:utility-data.ts


示例10: expect

  it('should return 403 if scope is not granted', () => {

    // given
    const authHeader = 'Bearer 4b70510f-be1d-4f0f-b4cb-edbca2c79d41';
    addAuthenticationEndpointWithoutRequiredScopes();

    // when
    const promise = fetch('http://127.0.0.1:30002/resource/user', {
      method: 'GET',
      headers: {
        authorization: authHeader
      }
    })
    .then((res) => {

      return res.status;
    });

    // then
    return expect(promise).to.become(HttpStatus.FORBIDDEN);
  });
开发者ID:zalando-incubator,项目名称:lib-oauth-tooling,代码行数:21,代码来源:middlewares.spec.ts


示例11: fetch

const createAction = (
  action: LikeAction,
  id: string,
  title?: string,
): Promise<StatusResponse> => {
  const url = new URL(
    'https://script.google.com/macros/s/AKfycbwErydNjqBnj4xo_AHcAro-UziMCuciiMEORMQMuJ-fxhk4XxE/exec',
  );

  url.searchParams.set('id', id);
  url.searchParams.set('action', action);
  if (title) {
    url.searchParams.set('description', title);
  }

  return fetch(url.toString()).then(result => {
    return {
      code: result.status,
      message: result.statusText,
    };
  });
};
开发者ID:ericmasiello,项目名称:synbydesign,代码行数:22,代码来源:likeService.ts


示例12: exec

async function exec() {
    const resp = await fetch(endpoint, {
        method: "POST",
        headers: {
            Authorization: `bearer ${authToken}`,
        },
        body: `{"query":${JSON.stringify(query)}}`,
    });
    if (resp.status !== 200) {
        throw new Error(`error, ${resp.status} ${await resp.text()}`);
    }
    const data = await resp.json();

    const text = data.data.search.nodes
        .filter((v: any) => ignoreOrgs.indexOf(v.repository.owner.login) === -1)
        .filter((v: any) => {
            const createdAt = new Date(v.createdAt);
            return start.getTime() <= createdAt.getTime() && createdAt.getTime() < end.getTime();
        })
        .map((v: any) => `* ${v.title} ${v.createdAt}\n    * ${v.url}`).join("\n");
    console.log(text);
}
开发者ID:vvakame,项目名称:til,代码行数:22,代码来源:index.ts


示例13: getUsers

async function getUsers(): Promise<void> {

  let usersRequest = await fetch(
    api,
    {
      headers: headers
    }
  );

  let usersResponse = await usersRequest.json();

  if (usersRequest.ok) {
    await Promise.all(usersResponse.map(async (user) => {
      await createUser(user.login);
      console.log(`User ${user.login} created`);
    }));
  }
  else {
    // Something horrible happened;
    console.error(usersResponse);
  }

}
开发者ID:Istar-Eldritch,项目名称:systemusers,代码行数:23,代码来源:index.ts


示例14: getStockSymbol

    getStockSymbol(input: string, callback: SClientCallback) {
        var url = `http://dev.markitondemand.com/Api/v2/Lookup/json?input=${input}`;

        fetch(url)
            .then(function(res) {
                if (res.status === 200) {
                    return res.json();
                }
                else {
                    callback(
                        {
                            url: res.url,
                            status: res.status,
                            statusText: res.statusText
                        }, null);
                }
            })
            .then(function(data) {
                if (callback) {
                    callback(null, data)
                }
            });
    }
开发者ID:plkumar,项目名称:StockBot,代码行数:23,代码来源:StockClient.ts


示例15: GetLUISInfo

 GetLUISInfo(sourceText: string, callback: LuisCallback) {
     var luisBaseUrl = "https://api.projectoxford.ai/luis/v1/application";
     var applicationId = "07c4c72e-d229-4c7b-96db-2034c036d30e";
     var subscriptionKey = "c2ba4a70587642b7a4cada97a40584ed";
     var requestUri = `${luisBaseUrl}?id=${applicationId}&subscription-key=${subscriptionKey}&q=${sourceText}`;
     fetch(requestUri).then((res) => {
         if (res.status === 200) {
             return res.json();
         }
         else {
             callback(
                 {
                     url: res.url,
                     status: res.status,
                     statusText: res.statusText
                 }, null);
         }
     }).then((data) => {
         if (callback) {
             callback(null, data)
         }
     });
 }
开发者ID:plkumar,项目名称:StockBot,代码行数:23,代码来源:luis-client.ts


示例16: async

const generateRundeckToken: () => Promise<string> = async () => {
  const date = new Date();

  const response = await _fetch(
    BASE_URL + '/api/25/token', {
      headers: {
        "X-Rundeck-Auth-Token": process.env.MASTER_RUNDECK_TOKEN,
        "accept": "application/json",
        "Content-type": "application/json"
      },
      body: {
        "user": date.getTime(),
        "role": [
          "ROLE_user"
        ],
        "duration": "10080m"
      }
    }
  ).json();

  const tokenInfo = response.token;
  return tokenInfo;
};
开发者ID:Shikugawa,项目名称:RoBaaS,代码行数:23,代码来源:rundeck.ts


示例17: export

  public async export(
    file: string,
    language: string,
    documentPath: string,
    options: any
  ) {
    language = language || this.config.language

    const query = [
      ['document_path', documentPath],
      ['document_format', this.config.format],
      ['order_by', options['order-by']],
      ['language', language]
    ]
      .map(([name, value]) => `${name}=${value}`)
      .join('&')

    const url = `${this.apiUrl}/export?${query}`
    const response = await fetch(url, {
      headers: this.authorizationHeader()
    })

    return this.writeResponseToFile(response, file)
  }
开发者ID:mirego,项目名称:accent-cli,代码行数:24,代码来源:document.ts


示例18: test

    test("Confirms user and clears key in redis", async () => {

        const url = await createConfirmEmail(
            process.env.TEST_HOST as string, // cast to string to satisfy typeScript
            userId as string, 
            redis
        );
    
        // make get request to the url to get "ok" to signal that user was 
        // updated
    
        const response = await fetch(url);
        const text = await response.text();
        expect(text).toEqual("ok");
        
        const user = await User.findOne({ where: {id: userId} });
        expect((user as User).confirmed).toBeTruthy();
    
        const chunks = url.split('/');
        const key = chunks[chunks.length - 1];
        const value = await redis.get(key);
        expect(value).toBeNull();
    
    })
开发者ID:itaygolan,项目名称:GraphQL-Typescript-Server,代码行数:24,代码来源:createEmailLink.test.ts


示例19: getPackages

 function getPackages(conn) {
     var requestUrl: string = conn.instanceUrl + '/_ui/common/apex/debug/ApexCSIAPI';
     var headers: any = {
         'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
         'Cookie': 'sid=' + conn.accessToken,
     };
     var body: string = 'action=EXTENT&extent=PACKAGES';
     return fetch(requestUrl, { method: 'POST', headers, body }).then(function (response) {
         if (response.status === 200) {
             return response.text();
         } else {
             vscode.window.forceCode.statusBarItem.text = response.statusText;
             return JSON.stringify({ PACKAGES: { packages: [] } });
         }
     }).then(function (json: string) {
         if (json.trim().startsWith('<')) {
             return [];
         } else {
             return JSON.parse(json.replace('while(1);\n', '')).PACKAGES.packages;
         }
     }).catch(function () {
         return [];
     });
 }
开发者ID:mgarf,项目名称:ForceCode,代码行数:24,代码来源:retrieve.ts


示例20: getStockPrice

 getStockPrice(symbol: string, callback: SClientCallback) {
     var url = `http://www.google.com/finance/info?q=${symbol}`;
     
     fetch(url)
     .then((res) =>{
         if (res.status === 200) {
                 return res.text();
             }
             else {
                 callback(
                     {
                         url: res.url,
                         status: res.status,
                         statusText: res.statusText
                     }, null);
             }
     }).then((data) => {
         data = data.substring(3); //remove "//" from response.
             var parsed = JSON.parse(data);
             if (callback) {
                 callback(null, parsed);
             }
     });
 }
开发者ID:plkumar,项目名称:StockBot,代码行数:24,代码来源:StockClient.ts



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript node-fetch.Headers类代码示例发布时间:2022-05-25
下一篇:
TypeScript Node.extend类代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap