Browser library compatible with Node.js request package

Overview

Browser Request: The easiest HTTP library you'll ever see

Browser Request is a port of Mikeal Rogers's ubiquitous and excellent [request][req] package to the browser.

Jealous of Node.js? Pining for clever callbacks? Request is for you.

Don't care about Node.js? Looking for less tedium and a no-nonsense API? Request is for you too.

browser support

Examples

Fetch a resource:

request('/some/resource.txt', function(er, response, body) {
  if(er)
    throw er;
  console.log("I got: " + body);
})

Send a resource:

request.put({uri:'/some/resource.xml', body:'<foo><bar/></foo>'}, function(er, response) {
  if(er)
    throw new Error("XML PUT failed (" + er + "): HTTP status was " + response.status);
  console.log("Stored the XML");
})

To work with JSON, set options.json to true. Request will set the Content-Type and Accept headers, and handle parsing and serialization.

request({method:'POST', url:'/db', body:'{"relaxed":true}', json:true}, on_response)

function on_response(er, response, body) {
  if(er)
    throw er
  if(result.ok)
    console.log('Server ok, id = ' + result.id)
}

Or, use this shorthand version (pass data into the json option directly):

request({method:'POST', url:'/db', json:{relaxed:true}}, on_response)

Convenient CouchDB

Browser Request provides a CouchDB wrapper. It is the same as the JSON wrapper, however it will indicate an error if the HTTP query was fine, but there was a problem at the database level. The most common example is 409 Conflict.

request.couch({method:'PUT', url:'/db/existing_doc', body:{"will_conflict":"you bet!"}}, function(er, resp, result) {
  if(er.error === 'conflict')
    return console.error("Couch said no: " + er.reason); // Output: Couch said no: Document update conflict.

  if(er)
    throw er;

  console.log("Existing doc stored. This must have been the first run.");
})

See the [Node.js Request README][req] for several more examples. Request intends to maintain feature parity with Node request (except what the browser disallows). If you find a discrepancy, please submit a bug report. Thanks!

Usage

Browserify

Browser Request is a [browserify][browserify]-enabled package.

First, add browser-request to your Node project

$ npm install browser-request

Next, make a module that uses the package.

// example.js - Example front-end (client-side) code using browser-request via browserify
//
var request = require('browser-request')
request('/', function(er, res) {
  if(!er)
    return console.log('browser-request got your root path:\n' + res.body)

  console.log('There was an error, but at least browser-request loaded and ran!')
  throw er
})

To build this for the browser, run it through browserify.

$ browserify --entry example.js --outfile example-built.js

Deploy example-built.js to your web site and use it from your page.

  <script src="example-built.js"></script> <!-- Runs the request, outputs the result to the console -->

License

Browser Request is licensed under the Apache 2.0 license.

Comments
  • Require issues (browserify)

    Require issues (browserify)

    Hi

    Thanks for this convenient library that allows me to use a single codebase on browser & node! I'm using this with browserify, but I've had to remove a few things from request.js:

    • require('./xmlhttprequest') — that file is not in the current directory
    • The check for XHR.name !== 'cXMLHttpRequest'
    • I also added a browserify key to package.json. A main key would help as well here.

    Do you understand the issues or do you want me to draft a pull request?

    opened by astro 10
  • simplify stuff

    simplify stuff

    this removes almost everything, including the xmlhttprequest polyfill. I couldn't make heads or tails of the previous build system (required ruby and makefiles).

    this adds browserling tests, and will make it a lot easier to contribute to this repo. we'll need to add back a cross browser xhr polyfill, but it can be done in a sane way with tests this time.

    at this time iriscouch/browser-request doesn't work in FF but this one does

    opened by maxogden 4
  • better cross domain errors

    better cross domain errors

    Given a cross domain request:

    request({url: "http://pizza.com/api"}, function(e,r,b) {
      console.log(e,r,b)
    })
    

    e and b are null

    request({url: "http://pizza.com/api", json:true}, function(e,r,b) {
      console.log(e,r,b)
    })
    

    e is a JSON parse syntax error and b is null

    Would it be possible to detect and return an error about the single origin policy?

    opened by maxogden 3
  • Request works in Chrome, fails in Firefox with

    Request works in Chrome, fails in Firefox with "CORS request rejected" error

    In Chrome the following code works. In Firefox I get the error : Error: CORS request rejected With the code :

    use strict';
    var request =require('browser-request');
    var url = 'http://docs.google.com/spreadsheets/export?id=1-on_GfmvaEcOk7HcWfKb8B6KFRv166RkLN2YmDEtDn4&exportFormat=csv';
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log('success fetch');
            console.log(response.statusCode);
            console.log(body);
        }else{
            console.log(error + ' ' + response.statusCode );
        }
    });
    
    opened by misterfresh 2
  • 0.3.0 - no more xmlhttprequest polyfill (for now)

    0.3.0 - no more xmlhttprequest polyfill (for now)

    this bumps the version to 0.3.0 so we can publish to npm. also fixes urls for the testling badge

    can you add em as a collaborator to this repo and also npm owners add browser-request maxogden? cheers

    opened by maxogden 2
  • Sending an image file using the form?

    Sending an image file using the form?

    Some encoding issue

    ---------------------------------702453823
    Content-Disposition: form-data; name="profile_picture"
    
    [object Object]
    ---------------------------------702453823--
    
    opened by EddieOne 1
  • request module work in browser

    request module work in browser

    hi, I tried the normal request module and browserified it. Everything worked fine in the browser. Am I missing something? Why would one use browser-request instead of request?

    Thank you

    opened by novellizator 1
  • Reference global.XMLHttpRequest directly so XMLHttpRequest can be mocked

    Reference global.XMLHttpRequest directly so XMLHttpRequest can be mocked

    • check for the existence of global.XMLHttpRequest directly
    • reference global.XMLHttpRequest constructor instead of the constructor that was dereferenced when the library was first parsed
    • reference global.XMLHttpRequest status properties directly instead of the properties of the prototype of the constructor that was dereferenced when the library was first parsed

    This will allow mocking libraries that rely on being able to replace the reference to global.XMLHttpRequest with a mock XMLHttpRequest object that can be programmatically manipulated.

    Such libraries include the jasmine-ajax plugin. I'm sure there are others.

    It's a little more typing, but it fixes a big bug.

    opened by cacieprins 1
  • Is anyone still maintaining this library?

    Is anyone still maintaining this library?

    With 30 Issues Opened and 31 Pull requests, I am wondering if this library is still maintained by anyone and if not, what could be the implications of using it in the long-term?

    opened by patrickptm 4
  • Support proxy option

    Support proxy option

    Hi there, how hard would it be to support proxy option, that is supported in the node request?

    I was thinking, we would just need to replace the host address in URL of each request with the proxy host/ip address and it should work, am I wrong?

    Use case: We're trying to switch from request to browser-request because of HTTP/2 support. We use this in Electron, so we have both node and browser environments.

    opened by jakubzitny 0
  • window.request is undefined

    window.request is undefined

    Following the Usage instructions it seems like I should be able to avoid using Browserify by loading the browser-request JS file directly in HTML like so <script src="node_modules/browser-request/index.js"></script> and then in another JS file that is loaded beneath it, using browser-request by calling window.request (HTML comment in Usage instructions reads "Assigns the module to window.request"). Apparently I am misinterpreting that because window.request is undefined. Can someone please explain to me how to use this without needing to use Node's require() and Browserify? I have confirmed that node_modules/browser-request/index.js is being loaded by the browser.

    Thank you.

    opened by maskedjellybean 0
  • Simple way to make a request sync?

    Simple way to make a request sync?

    By default browser-request is async but I don't see any obvious way to make it sync. I have two functions, getHTTP and HTTPExists, but I also want to make getHTTPSync and HTTPExistsSync.

    What are my options to make them sync?

    function HTTPExists(url, cb) {
      request({ url: resolve(url), method: 'HEAD' }, function(err, res) {
        if (err) return cb(null, false);
        cb(null, /4\d\d/.test(res.statusCode) === false);
      });
    }
    
    function getHTTP(url, cb) {
      request(resolve(url), function (error, response, body) {
        if (!error && response.statusCode == 200) {
          cb(null, body);
        } else {
          cb(error, body)
        }
      })
    }
    
    opened by 01AutoMonkey 1
  • formData support for PUT and POST

    formData support for PUT and POST

    Two fixes here:

    1. Method can be manually set via method: 'post', so we need the method check to be not case sensitive #63
    2. Sometimes form data is required for PUT requests
    opened by qvaqvaboo 1
Owner
Iris Couch
Iris Couch
Package fetcher is a bot messenger which gather npm packages by uploading either a json file (package.json) or a picture representing package.json. To continue...

package-fetcher Ce projet contient un boilerplate pour un bot messenger et l'executable Windows ngrok qui va permettre de créer un tunnel https pour c

AILI Fida Aliotti Christino 2 Mar 29, 2022
Browser-compatible JS library for running language models

Huggingface Transformers Running in the Browser This library enables you to run huggingface transformer models directly in the browser. It accomplishe

Frank A. Krueger 50 Jan 8, 2023
Typescript package compatible with python's pickle loads/dumps

picklefriend Typescript package compatible with python's pickle loads/dumps Installation npm i picklefriend Usage import { pickle } from 'picklefriend

null 4 Oct 27, 2022
Multi-platform node package bundle to a package.json.

dmpc Multi-platform node package bundle to a package.json. install ### npm mode npm i -g @kingsword/dmpc ### yarn mode yarn global add @kingsword/dmp

Kingsword 2 Oct 16, 2022
Learn Basic of Node Express Server and Git & Github by creating Pull Request in this repository.

hacktoberfest-express-server-2022 Learn Basic of Node Express Server and Git & Github by creating Pull Request in this repository. Special Note For Ev

NetScape-Web 3 Oct 6, 2022
Ajax library with XHR2, promises and request limit

qwest 4.5.0 ⚠ I finally decided to archive this repository. ⚠ At first, I developed Qwest because at the time other libraries were lacking of a proper

Aurélien Delogu 718 Sep 14, 2022
A minimalist Javascript library to perform AJAX POST and GET Request.

minAjax.js A minimalist Javascript library to perform AJAX POST and GET Request. #Check Pretty Documentation http://flouthoc.github.io/minAjax.js/ #Us

null 6 Apr 27, 2021
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
This package is for developers to be able to easily integrate bad word checking into their projects.\r This package can return bad words in array or regular expression (regex) form.

Vietnamese Bad Words This package is for developers to be able to easily integrate bad word checking into their projects. This package can return bad

Nguyễn Quang Sáng 8 Nov 3, 2022
This project uses JavaScript to request resources from PokeApi and Involvement API to display a stunning website about Pokemons.

POKEDEX CAPSTONE Web page used to retrieve information about Pokemons using Pokeapi v2 This project implements the involvement API and the Pokeapi to

Leonardo Pareja Pareja 7 Jun 13, 2022
An HTML, CSS and JavaScript project related to a leaderboard, where you can submit a specific score data using an API request

LeaderBoard-Project In this project we use Webpack dependecy and a external API for displaying the leaderboard data inside the dom. Built with HTML-CS

Nicolas Gonzalez 4 Mar 3, 2022
Request-Header-Parser-Microservice App for FreeCodeCamp Backend Challenge

API Project: Request Header Parser Microservice for freeCodeCamp User stories: I can get the IP address, preferred languages (from header Accept-Langu

Christotle Agholor 3 Mar 20, 2022
GitHub Action that posts the report in a comment on a GitHub Pull Request from coverage data generated by nyc (istanbul)

GitHub Action: Report NYC coverage GitHub Action that posts the report in a comment on a GitHub Pull Request from coverage data generated by nyc (ista

Sid 16 Nov 23, 2022
Automatically code review with ktlint result for pull request

GitHub Actions - ktlint-auto-review ?? Automatically reviewed on Pull Request with ktlint Inspired by ScaCap/action-ktlint but without reviewdog. Gett

MinJun Kweon 6 Dec 20, 2022
An action intended to run on pull request and post a comment summarizing any changes to DevCycle variables.

Overview With this Github action, information on which DevCycle features have been added or removed in a code change will be shown directly on each Pu

DevCycle 20 Jun 14, 2022
A plugin for Strapi Headless CMS that provides the ability to transform the API request or response.

strapi-plugin-transformer A plugin for Strapi that provides the ability to transform the API request and/or response. Requirements The installation re

daedalus 71 Jan 6, 2023
A GitHub app to report failed workflow job actions and notify pull request creator with custom report message for the failed workflow job.

Workflow Reporter A GitHub App built with Probot that reports failed workflow job actions and notify the pull request creator with custom report messa

Divyanshu Shekhar 14 Nov 12, 2022
🚀 NFTank (NFT tank for dummies) will allow developers to quickly request NFTs to personal wallets or smart contracts in just a few clicks.

??‍♂️ NFTank ?? NFTank (NFT tank for dummies) will allow developers to quickly request NFTs to personal wallets or smart contracts in just a few click

buidler's hub 8 Nov 8, 2022
Runs sfdx-scanner on a pull request and generates in-line comments with the findings.

sfdx-scan-pull-request Runs sfdx-scanner on a pull request and generates in-line comments with the findings. Inputs category Categor(ies) of rules to

Mitchell spano 27 Jan 7, 2023