How to use the node-fetch.Headers function in node-fetch

To help you get started, we’ve selected a few node-fetch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github adidas / mashery-toolbelt / src / masheryClient.js View on Github external
const { URL } = require('url');
const fetch = require('node-fetch');

require('dotenv').config();

const MASHERY_KEY = process.env.MASHERY_KEY;
const MASHERY_HOST = process.env.MASHERY_HOST;

// Common request headers
const RequestHeaders = new fetch.Headers({
  "Accept": "application/json",
  "Authorization": `Bearer ${MASHERY_KEY}`,
});

// Fetch HTTP Error Handler
function handleHTTPError(response) {
  if (!response.ok) {
    var message = `(${response.status}) ${response.statusText}\n\n`;
    const headers = response.headers['_headers'];

    for (var key in headers) {
      message += `${key}: ${headers[key]}\n`;
    }

    // response.text().then(data => console.log(data));
github microsoft / rushstack / apps / rush-lib / src / logic / InstallManager.ts View on Github external
private _queryIfReleaseIsPublished(registryUrl: string): Promise {
    let queryUrl: string = registryUrl;
    if (queryUrl[-1] !== '/') {
      queryUrl += '/';
    }
    // Note that the "@" symbol does not normally get URL-encoded
    queryUrl += RushConstants.rushPackageName.replace('/', '%2F');

    const userAgent: string = `pnpm/? npm/? node/${process.version} ${os.platform()} ${os.arch()}`;

    const headers: fetch.Headers = new fetch.Headers();
    headers.append('user-agent', userAgent);
    headers.append('accept', 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*');

    let agent: http.Agent | undefined = undefined;
    if (process.env.HTTP_PROXY) {
      agent = new HttpsProxyAgent(process.env.HTTP_PROXY);
    }

    return fetch
      .default(queryUrl, {
        headers: headers,
        agent: agent
      })
      .then((response: fetch.Response) => {
        if (!response.ok) {
          return Promise.reject(new Error('Failed to query'));
github hensm / fx_cast / app / src / bridge / airplay / auth.ts View on Github external
public async sendPostRequest (
            path: string
          , contentType?: string
          , data?: Buffer | string): Promise {

        // Create URL from base receiver URL and path
        const requestUrl = new URL(path, this.baseUrl);

        const requestHeaders = new Headers({
            "User-Agent": "AirPlay/320.20"
        });

        // Append Content-Type header if request has body
        if (data && contentType) {
            requestHeaders.append("Content-Type", contentType);
        }

        const response = await fetch(requestUrl.href, {
            method: "POST"
          , headers: requestHeaders
          , body: data
        });

        if (!response.ok) {
            throw new Error(`AirPlay request error: ${response.status}`);
github soyuka / rxrest / test / index.js View on Github external
it('should get all', function () {
    let params = new URLSearchParams()
    params.set('foo', 'bar')

    let headers = new Headers()
    headers.set('Accept', 'application/json')

    config.requestInterceptors.push(function (request) {
      expect(request.headers.has('Accept')).to.be.true
    })

    return rxrest.all('test')
    .getList(params, headers)
    .toPromise()
    .then(function (values) {
      expect(values).to.be.an.instanceof(RxRestCollection)
      for (let item of values) {
        expect(item).to.be.an.instanceof(RxRestItem)
        expect(item.URL).to.equal('http://localhost:3333/test/3')
        expect(item.$fromServer).to.be.true
      }
github SkygearIO / skygear-SDK-JS / packages / skygear-node-client / src / index.ts View on Github external
async function uploadData(
  method: string,
  url: string,
  headers: { name: string; value: string }[],
  data: Buffer | Readable
): Promise {
  const fetchHeaders = new Headers();
  for (const header of headers) {
    fetchHeaders.set(header.name, header.value);
  }
  const init = {
    method,
    headers: fetchHeaders,
    mode: "cors",
    body: data,
  };
  const response = await nodeFetch(url, init);
  return response.status;
}
github Severenit / figma-to-web / figma-to-style / lib / get-styles-artboard.js View on Github external
const URL = require('url');
const fetch = require('node-fetch');
const headers = new fetch.Headers();
const devToken = process.env.DEV_TOKEN;
headers.append('X-Figma-Token', devToken);

let type = process.argv[3] || 'files';

const getFiles = require('./get-files.js');
const getTeamsStyle = require('./get-teams-style.js')
const getFontStyles = require('./get-font-styles.js');
const getColorPlatte = require('./get-color-platte.js');
const getGrids = require('./get-grids.js');
const getEffect = require('./get-effect.js');

module.exports = async function (key, URLformat) {
	let figmaTreeStructure;
	let figmaId;
github sourcegraph / sourcegraph-vscode / src / graphql.ts View on Github external
async function requestGraphQL(
    graphQLDocument: string,
    variables: { [name: string]: any }
): Promise {
    const headers = new Headers()
    headers.append('User-Agent', 'Sourcegraph for Visual Studio Code')

    const accessToken = getAccessToken()
    if (accessToken) {
        headers.append('Authorization', `token ${accessToken}`)
    }

    const nameMatch = graphQLDocument.match(/^\s*(?:query|mutation)\s+(\w+)/)
    const graphqlUrl = getSourcegraphUrl() + '/.api/graphql' + (nameMatch ? '?' + nameMatch[1] : '')
    const init: RequestInit = {
        method: 'POST',
        headers,
        body: JSON.stringify({ query: graphQLDocument, variables }),
    }
    const resp = await fetch(graphqlUrl, init)
github entropic-dev / entropic / services / common / boltzmann / response.js View on Github external
function authneeded(message, status = 401, extraHeaders = {}) {
  const headers = new Headers({
    'www-authenticate': 'bearer',
    'content-type': 'application/json',
    ...extraHeaders
  });
  if (typeof message === 'string') {
    message = { message, code: 'authneeded' };
  }
  const r = new Response(JSON.stringify(message), { status, headers });
  return r;
}
github expo / expo-server-sdk-node / src / ExpoClient.ts View on Github external
async _requestAsync(url: string, options: RequestOptions): Promise {
    let requestBody: string | Buffer | undefined;

    let sdkVersion = require('../package.json').version;
    let requestHeaders = new Headers({
      Accept: 'application/json',
      'Accept-Encoding': 'gzip, deflate',
      'User-Agent': `expo-server-sdk-node/${sdkVersion}`,
    });

    if (options.body != null) {
      let json = JSON.stringify(options.body);
      assert(json != null, `JSON request body must not be null`);
      if (options.shouldCompress(json)) {
        requestBody = await _gzipAsync(Buffer.from(json));
        requestHeaders.set('Content-Encoding', 'gzip');
      } else {
        requestBody = json;
      }

      requestHeaders.set('Content-Type', 'application/json');
github btoles / semantix / src / services / github.service.js View on Github external
constructor({ config, owner, repositoryName }) {
        const url = config.apiBaseUrl();
        this.log = new Logger(config.verbose());
        this.owner = owner;
        this.repositoryName = repositoryName;
        this.baseURL = url.endsWith('/')
                     ? url.slice(0, -1)
                     : url;
        this.headers = new Headers({
            'User-Agent': 'semantix',
            Accept: 'application/vnd.github.v3+json',
            Authorization: `token ${config.accessToken()}`,
            'Content-Type': 'application/json'
        });
    }