GithubHelp home page GithubHelp logo

request-json's Introduction

About

Request is a great HTTP client for NodeJS, but if you deal only with JSON, things could be more straightforward. This lib aims to simplify Request usage for JSON only requests.

Install

Add it to your package.json file or run in your project folder:

npm install request-json --save

Build status

Build Status

How it works

request = require('request-json');
var client = request.createClient('http://localhost:8888/');

var data = {
  title: 'my title',
  content: 'my content'
};
client.post('posts/', data, function(err, res, body) {
  return console.log(res.statusCode);
});

client.get('posts/', function(err, res, body) {
  return console.log(body.rows[0].title);
});

data = {
  title: 'my new title'
};
client.put('posts/123/', data, function(err, res, body) {
  return console.log(res.statusCode);
});

client.del('posts/123/', function(err, res, body) {
  return console.log(res.statusCode);
});

data = {
  title: 'my patched title'
};
client.patch('posts/123/', data, function(err, res, body) {
  return console.log(res.statusCode);
});

Note: Previously you should call newClient() but now it is renamed to createClient(). You still can use newClient() though it will throw deprecation message.

Extra: files

data = {
  name: "test"
};
client.sendFile('attachments/', './test.png', data, function(err, res, body) {
  if (err) {
    return console.log(err);
  }
});

client.saveFile('attachments/test.png', './test-get.png', function(err, res, body) {
  if (err) {
    return console.log(err);
  }
});

sendFile can support file path, stream, array of file path and array of streams. Each file is stored with the key 'file + index' (file0, file1, file2...) in the request in case of array. For a single value, it is stored in the field with key 'file'. If you use a stream, it must have a "path" attribute containing its path or filename.

Extra: basic authentication

client.setBasicAuth('john', 'secret');
client.get('private/posts/', function(err, res, body) {
  return console.log(body.rows[0].title);
});

Extra: headers manipulation

client.headers['Cookie'] = 'Your cookie';

Extra: promises

client.get('posts/')
  .then(function(result) {
    console.log(result.res.statusCode);
    console.log(result.body); 
  }).catch(err) {
    console.log(err);
  }
});

Who uses it

request-json and request-json-light are downloaded more than 50 000 times each month. Here are the companies which use it for their API clients:

request-json's People

Contributors

aenario avatar cbupp avatar fabiosantoscode avatar frankrousseau avatar ifraixedes avatar jsilvestre avatar kblok avatar kloadut avatar miskun avatar nickh-nz avatar nono avatar pdehaan avatar pluma avatar poupotte avatar reverentgeek avatar stevetweeddale avatar vedi 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

request-json's Issues

Query String Authentication

A lot of other libraries I've seen don't support this, and it gets rather.. frustrating. I understand you've just written a thin wrapper around request but it does not hurt to ask.

Some of the APIs I use utilize query string authentication, rather than Authentication HTTP headers or basic auth. For example, the Riot API requires the appending of a query string key called api_key with your api key to the end of the URL. I really do like the syntax of request.headers['foo'] = bar.

Is there any way a similar syntax could be introduced for query strings so that I don't have to manually construct the query string each time? It gets more painful when there are query string options for the API in addition to the api_key to construct it.

CookieJar - TypeError: Cannot read property 'secure' of undefined

Unfortunately I cannot use jar effectively between clients. Thanks for any advice on how to get this working.

Test case:

request     = require 'request'
requestJson = require 'request-json'

jar         = request.jar()
client1     = requestJson.newClient 'http://localhost:3021', jar: jar

user        = email: '[email protected]', password: 'password'

client0.post '/register', user, (err, res, body) ->
    console.log "%j, %j, %j", err, res, body

client0.post '/login', user, (err, res, body) ->
    console.log "%j, %j, %j", err, res, body

client1     = requestJson.newClient 'http://localhost:3020', jar: jar

# Error thrown below this line:
client1.get '/profile', (err, res, body) ->
    console.log "%j, %j, %j", err, res, body    

Traceback:

TypeError: Cannot read property 'secure' of undefined
at CookieJar.getCookies (node_modules/request/node_modules/tough-cookie/lib/cookie.js:946:23)
    at CookieJar.getCookieString (node_modules/request/node_modules/tough-cookie/lib/cookie.js:1044:19)
    at Request.jar (node_modules/request-json/node_modules/request/request.js:1277:33)
    at Request.init (node_modules/request-json/node_modules/request/request.js:202:8)
    at new Request (node_modules/request-json/node_modules/request/request.js:97:8)
    at request (node_modules/request-json/node_modules/request/index.js:50:11)
    at JsonClient.exports.JsonClient.JsonClient.get (node_modules/request-json/main.js:105:14)

EDIT: Just wrote up this tiny wrapper of the request library which works just fine for my use-cases:

request = require 'request'

module.exports = (base='', jar=null) -> (method, route, payload=null) -> (cb) ->
    options =
        url: "#{base}#{route}"
        json: payload ? true
        jar: jar ? request.jar()
        method: method
    request options, (err, res, body) ->
        cb err, res, body

Does't support header gzip

I set
client.headers['Accept-Encoding'] = 'gzip';
and I get error
error occured: Error: Parsing error : Unexpected token in JSON at position 0, body= (�ZKo�8��W>]����"h�{�CoqI���!�Q�[��/)Ŷ$ӱ��yU�aМ9Cg>��ק���]�'_N5������B��M�,[�[���4+ʆw����t�M�y���E=�
w�����]�6ٞ~=�at��:��
Q�EB���y��������4�U���KW�m�/�
�岨.@fos}���<q������?w}�&]�[��s2�s��2M���9E�}zKnucW�٘H�%��܅Y�tg�zfUm�/��7e��X��i�<�1e}!ܷ��T�ThVTFU�2�ga����y�#�+w�,n�t{
��ꢑZ[]�26�ly�l,(� �,6P�-H�ӀA��P�Y�b�̳�?Ef�\�3����=��v/�u�)��ʖ���בa�Y��vQ� �Nj�{�q߲f+��2IhLXS��;������19�8��k9�;���#+�d��k�� ����<��,�a���l������lV��
Έ��81�I輸{zK�A�S=�����x��:B>�Sc��^^��
��o���}��-��c��
�X��C��p�D NH��P̉�d)ۃb�
/
aA� �a��H���@x�������#��`�����a�� ,}��z
,������[&�������z<OC��Q�Q�Ջ����q����y��qߣ=��T-���rh�X�U
�c
C���e!c�����3�0P�W�A��M�r��9�@yh��wl�1׻����ޭ⟠G��y�2㩇�S��cdC��W�BeKy��R
��+
ME�d��,I}��%�E��vZ+m��~����=�Q�x2,v�WB&�kO

U데�r�p�}f�󄶁M��g��f�8����38����F F����@ ��p�5�ChO��Wu���^�p|h�.��#����åg���2֞׸�7�=����x<�Y"�����I�}r��T��A^��S���1�b�df� �h (��GfĀN�%�$C����:W�f������x�،�����TA�3���c�x-lx�,�n>����պ͕��u������23- at Object.parseBody (/Users/wangbinxiang/nodejs/SaasSubAdminFrontEnd/node_modules/request-json/main.js:67:19) at Request._callback (/Users/wangbinxiang/nodejs/SaasSubAdminFrontEnd/node_modules/request-json/main.js:148:26) at Request.self.callback (/Users/wangbinxiang/nodejs/SaasSubAdminFrontEnd/node_modules/request-json/node_modules/request/request.js:187:22)

Can your support gzip?

jar support?

How do I sent a jar (created with request.jar()) along with every request sent from the request-json client?

Digest Authentication

Where is the best place to start for enabling digest authentication. "request" supports it so I was guessing it shouldn't be to hard to add. Thanks!

Error: Parsing error: Unexpected token O in JSON at position 0 on PUT request

Jo!

My PUT request works in the server - I get a 200 and positive results. But the http client I create has complains over my request and it actually throws an error.

Error: Parsing error : Unexpected token O in JSON at position 0

It seems to be an issue that originates from auto stringifying of JSON, but I can not find how to resolve...

My request looks like this:

        const dataObj = {name: 'my-new-name'}
        client.put('my-url', dataObj, (err, res, body) => {
  		if (err) {
  			this.snack.isOpen = true;
  			this.snack.message = "The operation couldn't be handled";
  			console.log('error!', err);
  		} else {
  			this.snack.isOpen = true;
  			this.snack.message = 'The virtualization is successfully updated';
  			console.log(res.statusCode);
  		}
	});

So what shall I do to make it work well?

Thanks!

Nested objects aren't returned v0.3.5

It appears that there is a bug in "get"ing large json content.

example:

object.children[0].object.children ( last nested children array of object is empty with zero elements).

In comparison i called the same endpoint using request npm, and JSON.parse(body) , i was able to get nested elements but not with this library.
thanks

No head method on client

Hello !

I can't seem to find how to send head requests with request-json, but the basic request module has this method available.
Am I doing something wrong ?

client.head('/api/example', function(err, res, body){
    ...
}

I get this error message in the console

TypeError: Object #<JsonClient> has no method 'head'

Thanks for your help !
In the meantime I am using the basic 'request' module

delete request has no body

The delete request does not allow a request body! Is there another way I can send a delete request with a body?

sendFile is not JSON parsing the resulting body

When using .sendFile() the result body is not being JSON parsed according to this logic.

For a true server-end JSON API, it's really weird to expect this kind of response or behavior in my opinion that a response from file upload would be in text-form and not JSON form like everything else.

At the very least give us the option of forcing this.

Synchronous Requests

Hi there, love the plugin. Very simple and elegant.

I'm having some trouble using it for a synchronous request to my api though.

I've got the following:

var MyAPI = require('request-json').newClient('https://api.myapp.com');

function Client(){
    this.test = 'test';
}

Client.prototype.request = function(params){

    var request = {
        test: this.test,
        params : params
    }

    MyAPI.post('/', request, function(error, response, body){
        console.log(body);
        return body;
    });

}

The console.log(body) produces the response that I'm after to my server console. But, it's not returning the same result from the post request using the return body; line.

Any idea how to force this to be a synchronous request and have its callback trigger the return of my Client.prototype.request method.

Thanks for any help.

Using outdated Request module

The Request module that is currently being used by the project (2.74.0) is using a vulnerable release of Hawk (with Hoek as a deep dependency) according to the NSP checker.

The Request module has patched this in version 2.82.0 of their project, could you update using this version as a minimum? Thanks.

add .delete method

it would be nice to also have a .delete method (same as .del but much more intuitive)

SendFile & SaveFile

There is no tests for sendFile & saveFile.

In saveFile, we attempt to parseBody even if it is raw data, which trigger an error in version 0.3.1.

Moreover I need to add a sendFiles (with multiple files being sent) for cozy-photos tests.

I will work in this issue

HTTP/S proxy support?

  • I have configured my ENV variables
  • I have also set the same using npm config inside ~/.npmrc.

The requests raise an ECONNRESET. Do I need to pass any parameters while calling the createClient function?

Contributors

Hi @aenario @kblok @PiPeep @poupotte @fabiosantoscode,

I'm going to fill the Contributors field of the package.json. I would like to know if you want to be included into that list. If the answer is yes, reply to this issue.

Thank you all for your contributions,

Frank

callback called twice

With current try-catch structure for JSON parsing, the callback will be called twice if an error is thrown within the callback.

headers converted to lowercase

I've noticed that adding headers to requests using request-json clientside (perhaps via node as well) causes the headers name to be converted to lowercase, i.e. adding the following header:

{ Authorization: Bearer ${token} }

... results in the following header:

authorization: Bearer ${token}

Not sure if this is an issue with services, but it's disconcerting that request-json appears to be modifying my headers.

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.