Code Monkey home page Code Monkey logo

electron-request's Introduction

English | 简体中文

electron-request

Zero-dependency, Lightweight HTTP request client for Electron or Node.js

Why electron-request ?

Electron-request uses its built-in net module in Electron environment and uses its built-in HTTP module in Node.js environment.

Net module is used in electron to better support proxy, authentication, traffic monitoring proxies and other features. Please refer to net for details.

Features

  • Zero-dependency, Lightweight
  • Quick start, similar window.fetch
  • No need to import other libraries, support file download progress and file verification
  • Support to run on Electron or Node.js, use Electron's net module first
  • Unified error handling

Install

npm install electron-request --save
# or
yarn add electron-request

Usage

import request from 'electron-request';

void (async () => {
  const url = 'https://github.com/';
  const defaultOptions = {
    method: 'GET',
    body: null,
    followRedirect: true,
    maxRedirectCount: 20,
    timeout: 0,
    size: 0,
  };
  const response = await request(url, defaultOptions);
  const text = await response.text();
})();

API

request(url[, options])

  • url: Request URL

  • options: Options

    interface Options {
      /**
       * Request method
       * @default 'GET'
       */
      method?: string;
      /**
       * Request body
       * @default null
       */
      body?: string | null | Buffer | Stream;
      /**
       * Request headers
       */
      headers?: Record<string, string | string[]>;
      /**
       * Request query
       */
      query?: Record<string, string>;
      /**
       * Allow redirect
       * @default true
       */
      followRedirect?: boolean;
      /**
       * Maximum redirect count. 0 to not follow redirect
       * @default 20
       */
      maxRedirectCount?: number;
      /**
       * Request/Response timeout in ms. 0 to disable
       * @default 0
       */
      timeout?: number;
      /**
       * Maximum response body size in bytes. 0 to disable
       * @default 0
       */
      size?: number;
      /**
       * Whether to use nodejs native request
       * @default false
       */
      useNative?: boolean;
    
      // Docs: https://www.electronjs.org/docs/api/client-request#new-clientrequestoptions
    
      /**
       * Only in Electron. When use authenticated HTTP proxy, username to use to authenticate
       */
      username?: string;
      /**
       * Only in Electron. When use authenticated HTTP proxy, password to use to authenticate
       */
      password?: string;
      /**
       * Only in Electron. Whether to send cookies with this request from the provided session
       * @default true
       */
      useSessionCookies?: boolean;
      /**
       * Only in Electron. The Session instance with which the request is associated
       * @default electron.session.defaultSession
       */
      session?: Session;
    }

Response

interface Response {
  /** Whether the response was successful (status in the range 200-299) */
  ok: boolean;
  /** Response status code */
  statusCode: number;
  /** Response headers */
  headers: Record<string, string | string[]>;
  /** Return origin stream */
  stream: Stream;
  /** Decode response as ArrayBuffer */
  arrayBuffer(): Promise<ArrayBuffer>;
  /** Decode response as Blob */
  blob(): Promise<Blob>;
  /** Decode response as text */
  text(): Promise<string>;
  /** Decode response as json */
  json<T>(): Promise<T>;
  /** Decode response as buffer */
  buffer(): Promise<Buffer>;
  /**
   * Download file to destination
   * @param {Writable} destination Writable destination stream
   * @param {ProgressCallback=} onProgress Download progress callback
   * @param {ValidateOptions=} validateOptions Validate options
   */
  download: (
    destination: Writable,
    onProgress?: ProgressCallback,
    validateOptions?: ValidateOptions,
  ) => Promise<void>;
}

/** Download progress information */
interface ProgressInfo {
  /** Total file bytes */
  total: number;
  /** Delta file bytes */
  delta: number;
  /** Transferred file bytes */
  transferred: number;
  /** Transferred percentage */
  percent: number;
  /** Bytes transferred per second */
  bytesPerSecond: number;
}

License

MIT License

electron-request vs. the Competition

Package Size
request request package size
axios axios package size
node-fetch node-fetch package size
request-pure request-pure package size
electron-request electron-request package size

electron-request's People

Contributors

muneale avatar zacharyl2 avatar zkqiang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

electron-request's Issues

Pathname is duplicated when sending request

Hi,
When sending a request with an URL that contains an additional path name, e.g.

https://my-domain.com/path

The resulting URL in the request ends up being:

https://my-domain.com/path/path

I guess this behavior was introduced with the latest change in file RequestClient.ts L44:

 url: `${requestURL}${pathname}${search || ''}`,

The URL for the final request is constructed from the incoming URL (which already contains the path) and the pathname extracted by the URL class, resulting in a duplicate path - or am I missing something here?

If you like, I could also try to create a pull request with the fix.

Thank you and best regards,
Patric

get请求查询参数丢失

发起一个get请求,携带query,我已经断点查询到 options 中的 path 为 '/api?count=2',但实际发出去的请求只有 '/api',查询参数丢失了,这是怎么回事?

About basic auth

Hi, I am replacing axios with electron-request recently, when some requests use auth option(which from axios options about basic auth), I am not sure if it corresponds to username and password, when I try, the apis that can be accessed normally before returns 401. Thanks.

cloudflare issue

I'm getting cloudflare challenge when I use this library.

I'm not getting any cloudflare issue when I use the net.request using electron

SyntaxError: Unexpected token (20:10)

ERROR in ./node_modules/electron-request/dist/index.es.js

image

I tried to reinstall this and remove node_modules, but it didn't work

webpack config (part)

{
    test: /\.(m?js|node)$/,
    parser: { amd: false },
    use: {
      loader: '@marshallofsound/webpack-asset-relocator-loader',
      options: {
        outputAssetBase: 'native_modules',
      },
    },
  },

URL编码问题

node: v21.1.0
electron: 25.8.0

  async test() {
    let url = 'https://xxxx/yyyyy'
    let query = {
      data1: 'abc:edf'
    }
    // let fullUrl = this.getQueryUrlOfApi(url, query)
    try {
      let response = await request(url, {
        method: 'GET',
        query: query
      })
      // let response = await request(fullUrl, {
      //   method: 'GET'
      // })
      return await response.json()
    } catch (e) {
      return {
        success: false,
        message: e.toString()
      }
    }
  }
  getQueryUrlOfApi(url, query) {
    const parsedURL = new URL(url)
    const { searchParams } = parsedURL
    for (const [queryKey, queryValue] of Object.entries(query)) {
      searchParams.set(encodeURIComponent(queryKey), queryValue)
    }
    return parsedURL.href
  }

query参数里的“:”编码有问题,通过electron的session.defaultSession.webRequest.onBeforeSendHeaders确实能看到最后被编码成了“%253A”,所以不得不使用getQueryUrlOfApi防止重复编码两次。
可能是我没找到相关的设置,也可能是新版electron会自动编码URL?

你好,为什么会出现“Module parse failed: Unexpected token”错误

 error  in ./node_modules/electron-request/dist/index.es.js

Module parse failed: Unexpected token (130:8)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| };
| class Headers {
>     map = new Map();
|     constructor(init = {}) {
|         for (const [key, value] of Object.entries(init)) {

我用的是vue

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.