Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🏊🏾 Simplified HTTP request client.

License

NotificationsYou must be signed in to change notification settings

cypress-io/request

 
 

Repository files navigation

npm package

This is a fork ofrequest for use inCypress.

Super simple to use

Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.

constrequest=require('@cypress/request');request('http://www.google.com',function(error,response,body){console.error('error:',error);// Print the error if one occurredconsole.log('statusCode:',response&&response.statusCode);// Print the response status code if a response was receivedconsole.log('body:',body);// Print the HTML for the Google homepage.});

Table of contents

Request also offersconvenience methods likerequest.defaults andrequest.post, and there arelots ofusage examples and severaldebugging techniques.


Streaming

You can stream any response to a file stream.

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this caseapplication/json) and use the propercontent-type in the PUT request (if the headers don’t already provide one).

fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))

Request can alsopipe to itself. When doing so,content-type andcontent-length are preserved in the PUT headers.

request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

Request emits a "response" event when a response is received. Theresponse argument will be an instance ofhttp.IncomingMessage.

request.get('http://google.com/img.png').on('response',function(response){console.log(response.statusCode)// 200console.log(response.headers['content-type'])// 'image/png'}).pipe(request.put('http://mysite.com/img.png'))

To easily handle errors when streaming requests, listen to theerror event before piping:

request.get('http://mysite.com/doodle.png').on('error',function(err){console.error(err)}).pipe(fs.createWriteStream('doodle.png'))

Now let’s get fancy.

http.createServer(function(req,resp){if(req.url==='/doodle.png'){if(req.method==='PUT'){req.pipe(request.put('http://mysite.com/doodle.png'))}elseif(req.method==='GET'||req.method==='HEAD'){request.get('http://mysite.com/doodle.png').pipe(resp)}}})

You can alsopipe() fromhttp.ServerRequest instances, as well as tohttp.ServerResponse instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:

http.createServer(function(req,resp){if(req.url==='/doodle.png'){constx=request('http://mysite.com/doodle.png')req.pipe(x)x.pipe(resp)}})

And sincepipe() returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)

req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)

Also, none of this new functionality conflicts with requests previous features, it just expands them.

constr=request.defaults({'proxy':'http://localproxy.com'})http.createServer(function(req,resp){if(req.url==='/doodle.png'){r.get('http://google.com/doodle.png').pipe(resp)}})

You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.

back to top


Promises & Async/Await

request supports both streaming and callback interfaces natively. If you'd likerequest to return a Promise instead, you can use an alternative interface wrapper forrequest. These wrappers can be useful if you prefer to work with Promises, or if you'd like to useasync/await in ES2017.

Several alternative interfaces are provided by the request team, including:

Also,util.promisify, which is available from Node.js v8.0 can be used to convert a regular function that takes a callback to return a promise instead.

back to top


Forms

request supportsapplication/x-www-form-urlencoded andmultipart/form-data form uploads. Formultipart/related refer to themultipart API.

application/x-www-form-urlencoded (URL-Encoded Forms)

URL-encoded forms are simple.

request.post('http://service.com/upload',{form:{key:'value'}})// orrequest.post('http://service.com/upload').form({key:'value'})// orrequest.post({url:'http://service.com/upload',form:{key:'value'}},function(err,httpResponse,body){/* ... */})

multipart/form-data (Multipart Form Uploads)

Formultipart/form-data we use theform-data library by@felixge. For the most cases, you can pass your upload form data via theformData option.

constformData={// Pass a simple key-value pairmy_field:'my_value',// Pass data via Buffersmy_buffer:Buffer.from([1,2,3]),// Pass data via Streamsmy_file:fs.createReadStream(__dirname+'/unicycle.jpg'),// Pass multiple values /w an Arrayattachments:[fs.createReadStream(__dirname+'/attachment1.jpg'),fs.createReadStream(__dirname+'/attachment2.jpg')],// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}// Use case: for some types of streams, you'll need to provide "file"-related information manually.// See the `form-data` README for more information about options: https://github.com/form-data/form-datacustom_file:{value:fs.createReadStream('/dev/urandom'),options:{filename:'topsecret.jpg',contentType:'image/jpeg'}}};request.post({url:'http://service.com/upload',formData:formData},functionoptionalCallback(err,httpResponse,body){if(err){returnconsole.error('upload failed:',err);}console.log('Upload successful!  Server responded with:',body);});

For advanced cases, you can access the form-data object itself viar.form(). This can be modified until the request is fired on the next cycle of the event-loop. (Note that this callingform() will clear the currently set form data for that request.)

// NOTE: Advanced use-case, for normal use see 'formData' usage aboveconstr=request.post('http://service.com/upload',functionoptionalCallback(err,httpResponse,body){...})constform=r.form();form.append('my_field','my_value');form.append('my_buffer',Buffer.from([1,2,3]));form.append('custom_file',fs.createReadStream(__dirname+'/unicycle.jpg'),{filename:'unicycle.jpg'});

See theform-data README for more information & examples.

multipart/related

Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of amultipart/related request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them astrue to your request options.

request({method:'PUT',preambleCRLF:true,postambleCRLF:true,uri:'http://service.com/upload',multipart:[{'content-type':'application/json',body:JSON.stringify({foo:'bar',_attachments:{'message.txt':{follows:true,length:18,'content_type':'text/plain'}}})},{body:'I am an attachment'},{body:fs.createReadStream('image.png')}],// alternatively pass an object containing additional optionsmultipart:{chunked:false,data:[{'content-type':'application/json',body:JSON.stringify({foo:'bar',_attachments:{'message.txt':{follows:true,length:18,'content_type':'text/plain'}}})},{body:'I am an attachment'}]}},function(error,response,body){if(error){returnconsole.error('upload failed:',error);}console.log('Upload successful!  Server responded with:',body);})

back to top


HTTP Authentication

request.get('http://some.server.com/').auth('username','password',false);// orrequest.get('http://some.server.com/',{'auth':{'user':'username','pass':'password','sendImmediately':false}});// orrequest.get('http://some.server.com/').auth(null,null,true,'bearerToken');// orrequest.get('http://some.server.com/',{'auth':{'bearer':'bearerToken'}});

If passed as an option,auth should be a hash containing values:

  • user ||username
  • pass ||password
  • sendImmediately (optional)
  • bearer (optional)

The method form takes parametersauth(username, password, sendImmediately, bearer).

sendImmediately defaults totrue, which causes a basic or bearerauthentication header to be sent. IfsendImmediately isfalse, thenrequest will retry with a proper authentication header after receiving a401 response from the server (which must contain aWWW-Authenticate headerindicating the required authentication method).

Note that you can also specify basic authentication using the URL itself, asdetailed inRFC 1738. Simply pass theuser:password before the host with an@ sign:

constusername='username',password='password',url='http://'+username+':'+password+'@some.server.com';request({url},function(error,response,body){// Do more stuff with 'body' here});

Digest authentication is supported, but it only works withsendImmediatelyset tofalse; otherwiserequest will send basic authentication on theinitial request, which will probably cause the request to fail.

Bearer authentication is supported, and is activated when thebearer value isavailable. The value may be either aString or aFunction returning aString. Using a function to supply the bearer token is particularly useful ifused in conjunction withdefaults to allow a single function to supply thelast known token at the time of sending a request, or to compute one on the fly.

back to top


Custom HTTP Headers

HTTP Headers, such asUser-Agent, can be set in theoptions object.In the example below, we call the github API to find out the numberof stars and forks for the request repository. This requires acustomUser-Agent header as well as https.

constrequest=require('request');constoptions={url:'https://api.github.com/repos/cypress-io/request',headers:{'User-Agent':'request'}};functioncallback(error,response,body){if(!error&&response.statusCode==200){constinfo=JSON.parse(body);console.log(info.stargazers_count+" Stars");console.log(info.forks_count+" Forks");}}request(options,callback);

back to top


Proxies

If you specify aproxy option, then the request (and any subsequentredirects) will be sent via a connection to the proxy server.

If your endpoint is anhttps url, and you are using a proxy, thenrequest will send aCONNECT request to the proxy serverfirst, andthen use the supplied connection to connect to the endpoint.

That is, first it will make a request like:

HTTP/1.1 CONNECT endpoint-server.com:80Host: proxy-server.comUser-Agent: whatever user agent you specify

and then the proxy server make a TCP connection toendpoint-serveron port80, and return a response that looks like:

HTTP/1.1 200 OK

At this point, the connection is left open, and the client iscommunicating directly with theendpoint-server.com machine.

Seethe wikipedia page on HTTP Tunnelingfor more information.

By default, when proxyinghttp traffic, request will simply make astandard proxiedhttp request. This is done by making theurlsection of the initial line of the request a fully qualified url tothe endpoint.

For example, it will make a single request that looks like:

HTTP/1.1 GET http://endpoint-server.com/some-urlHost: proxy-server.comOther-Headers: all go hererequest body or whatever

Because a pure "http over http" tunnel offers no additional securityor other features, it is generally simpler to go with astraightforward HTTP proxy in this case. However, if you would liketo force a tunneling proxy, you may set thetunnel option totrue.

You can also make a standard proxiedhttp request by explicitly settingtunnel : false, butnote that this will allow the proxy to see the trafficto/from the destination server.

If you are using a tunneling proxy, you may set theproxyHeaderWhiteList to share certain headers with the proxy.

You can also set theproxyHeaderExclusiveList to share certainheaders only with the proxy and not with destination host.

By default, this set is:

acceptaccept-charsetaccept-encodingaccept-languageaccept-rangescache-controlcontent-encodingcontent-languagecontent-lengthcontent-locationcontent-md5content-rangecontent-typeconnectiondateexpectmax-forwardspragmaproxy-authorizationreferertetransfer-encodinguser-agentvia

Note that, when using a tunneling proxy, theproxy-authorizationheader and any headers from customproxyHeaderExclusiveList arenever sent to the endpoint server, but only to the proxy server.

Controlling proxy behaviour using environment variables

The following environment variables are respected byrequest:

  • HTTP_PROXY /http_proxy
  • HTTPS_PROXY /https_proxy
  • NO_PROXY /no_proxy

WhenHTTP_PROXY /http_proxy are set, they will be used to proxy non-SSL requests that do not have an explicitproxy configuration option present. Similarly,HTTPS_PROXY /https_proxy will be respected for SSL requests that do not have an explicitproxy configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using theproxy configuration option. Furthermore, theproxy configuration option can be explicitly set to false / null to opt out of proxying altogether for that request.

request is also aware of theNO_PROXY/no_proxy environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to* to opt out of the implicit proxy configuration of the other environment variables.

Here's some examples of validno_proxy values:

  • google.com - don't proxy HTTP/HTTPS requests to Google.
  • google.com:443 - don't proxy HTTPS requests to Google, butdo proxy HTTP requests to Google.
  • google.com:443, yahoo.com:80 - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo!
  • * - ignorehttps_proxy/http_proxy environment variables altogether.

back to top


UNIX Domain Sockets

request supports making requests toUNIX Domain Sockets. To make one, use the following URL scheme:

/* Pattern */'http://unix:SOCKET:PATH'/* Example */request.get('http://unix:/absolute/path/to/unix.socket:/request/path')

Note: TheSOCKET path is assumed to be absolute to the root of the host file system.

back to top


TLS/SSL Protocol

TLS/SSL Protocol options, such ascert,key andpassphrase, can beset directly inoptions object, in theagentOptions property of theoptions object, or even inhttps.globalAgent.options. Keep in mind that, althoughagentOptions allows for a slightly wider range of configurations, the recommended way is viaoptions object directly, as usingagentOptions orhttps.globalAgent.options would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent).

constfs=require('fs'),path=require('path'),certFile=path.resolve(__dirname,'ssl/client.crt'),keyFile=path.resolve(__dirname,'ssl/client.key'),caFile=path.resolve(__dirname,'ssl/ca.cert.pem'),request=require('request');constoptions={url:'https://api.some-server.com/',cert:fs.readFileSync(certFile),key:fs.readFileSync(keyFile),passphrase:'password',ca:fs.readFileSync(caFile)};request.get(options);

Usingoptions.agentOptions

In the example below, we call an API that requires client side SSL certificate(in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol:

constfs=require('fs'),path=require('path'),certFile=path.resolve(__dirname,'ssl/client.crt'),keyFile=path.resolve(__dirname,'ssl/client.key'),request=require('request');constoptions={url:'https://api.some-server.com/',agentOptions:{cert:fs.readFileSync(certFile),key:fs.readFileSync(keyFile),// Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:// pfx: fs.readFileSync(pfxFilePath),passphrase:'password',securityOptions:'SSL_OP_NO_SSLv3'}};request.get(options);

It is able to force using SSLv3 only by specifyingsecureProtocol:

request.get({url:'https://api.some-server.com/',agentOptions:{secureProtocol:'SSLv3_method'}});

It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs).This can be useful, for example, when using self-signed certificates.To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to theagentOptions.The certificate the domain presents must be signed by the root certificate specified:

request.get({url:'https://api.some-server.com/',agentOptions:{ca:fs.readFileSync('ca.cert.pem')}});

Theca value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect tohttps://api.some-server.com which presents a key chain consisting of:

  1. its own public key, which is signed by:
  2. an intermediate "Corp Issuing Server", that is in turn signed by:
  3. a root CA "Corp Root CA";

you can configure your request as follows:

request.get({url:'https://api.some-server.com/',agentOptions:{ca:[fs.readFileSync('Corp Issuing Server.pem'),fs.readFileSync('Corp Root CA.pem')]}});

back to top


Support for HAR 1.2

Theoptions.har property will override the values:url,method,qs,headers,form,formData,body,json, as well as construct multipart data and read files from disk whenrequest.postData.params[].fileName is present without a matchingvalue.

A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching.

constrequest=require('request')request({// will be ignoredmethod:'GET',uri:'http://www.google.com',// HTTP Archive Request Objecthar:{url:'http://www.mockbin.com/har',method:'POST',headers:[{name:'content-type',value:'application/x-www-form-urlencoded'}],postData:{mimeType:'application/x-www-form-urlencoded',params:[{name:'foo',value:'bar'},{name:'hello',value:'world'}]}}})// a POST request will be sent to http://www.mockbin.com// with body an application/x-www-form-urlencoded body:// foo=bar&hello=world

back to top


request(options, callback)

The first argument can be either aurl or anoptions object. The only required option isuri; all others are optional.

  • uri ||url - fully qualified uri or a parsed url object fromurl.parse()
  • baseUrl - fully qualified uri string used as the base url. Most useful withrequest.defaults, for example when you want to do many requests to the same domain. IfbaseUrl ishttps://example.com/api/, then requesting/end/point?test=true will fetchhttps://example.com/api/end/point?test=true. WhenbaseUrl is given,uri must also be a string.
  • method - http method (default:"GET")
  • headers - http headers (default:{})

  • qs - object containing querystring values to be appended to theuri
  • qsParseOptions - object containing options to pass to theqs.parse method. Alternatively pass options to thequerystring.parse method using this format{sep:';', eq:':', options:{}}
  • qsStringifyOptions - object containing options to pass to theqs.stringify method. Alternatively pass options to thequerystring.stringify method using this format{sep:';', eq:':', options:{}}. For example, to change the way arrays are converted to query strings using theqs module pass thearrayFormat option with one ofindices|brackets|repeat
  • useQuerystring - if true, usequerystring to stringify and parsequerystrings, otherwise useqs (default:false). Set this option totrue if you need arrays to be serialized asfoo=bar&foo=baz instead of thedefaultfoo[0]=bar&foo[1]=baz.

  • body - entity body for PATCH, POST and PUT requests. Must be aBuffer,String orReadStream. Ifjson istrue, thenbody must be a JSON-serializable object.
  • form - when passed an object or a querystring, this setsbody to a querystring representation of value, and addsContent-type: application/x-www-form-urlencoded header. When passed no options, aFormData instance is returned (and is piped to request). See "Forms" section above.
  • formData - data to pass for amultipart/form-data request. SeeForms section above.
  • multipart - array of objects which contain their own headers andbodyattributes. Sends amultipart/related request. SeeForms sectionabove.
    • Alternatively you can pass in an object{chunked: false, data: []} wherechunked is used to specify whether the request is sent inchunked transfer encodingIn non-chunked requests, data items with body streams are not allowed.
  • preambleCRLF - append a newline/CRLF before the boundary of yourmultipart/form-data request.
  • postambleCRLF - append a newline/CRLF at the end of the boundary of yourmultipart/form-data request.
  • json - setsbody to JSON representation of value and addsContent-type: application/json header. Additionally, parses the response body as JSON.
  • jsonReviver - areviver function that will be passed toJSON.parse() when parsing a JSON response body.
  • jsonReplacer - areplacer function that will be passed toJSON.stringify() when stringifying a JSON request body.

  • auth - a hash containing valuesuser ||username,pass ||password, andsendImmediately (optional). See documentation above.
  • hawk - options forHawk signing. Thecredentials key must contain the necessary signing info,see hawk docs for details.
  • aws -object containing AWS signing information. Should have the propertieskey,secret, and optionallysession (note that this only works for services that require session as part of the canonical string). Also requires the propertybucket, unless you’re specifying yourbucket as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parametersign_version with value4 otherwise the default is version 2. If you are using SigV4, you can also include aservice property that specifies the service name.Note: you need tonpm install aws4 first.
  • httpSignature - options for theHTTP Signature Scheme usingJoyent's library. ThekeyId andkey properties must be specified. See the docs for other options.

  • followRedirect - follow HTTP 3xx responses as redirects (default:true). This property can also be implemented as function which getsresponse object as the first argument.
    • (synchronous usage) It should returntrue if redirects should continue orfalse otherwise. If it returns a url string, the destination of the redirect will be overridden.
    • (async callback usage) If the function has two arguments, it will be treated as an asynchronous function and will be passed a callback as the second argument. Invoke the callback with an error (null if no error) and the boolean/url result as the second.
    • (async promise usage) Return a promise that resolves to the boolean/url result.
  • followAllRedirects - follow non-GET HTTP 3xx responses as redirects (default:false)
  • followOriginalHttpMethod - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default:false)
  • maxRedirects - the maximum number of redirects to follow (default:10)
  • removeRefererHeader - removes the referer header when a redirect happens (default:false).Note: if true, referer header set in the initial request is preserved during redirect chain.
  • allowInsecureRedirect - allows cross-protocol redirects (HTTP to HTTPS and vice versa).Warning: may lead to bypassing anti SSRF filters (default:false)

  • encoding - encoding to be used onsetEncoding of response data. Ifnull, thebody is returned as aBuffer. Anything else(including the default value ofundefined) will be passed as theencoding parameter totoString() (meaning this is effectivelyutf8 by default). (Note: if you expect binary data, you should setencoding: null.)
  • gzip - iftrue, add anAccept-Encoding header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response.Note: Automatic decoding of the response content is performed on the body data returned throughrequest (both through therequest stream and passed to the callback function) but is not performed on theresponse stream (available from theresponse event) which is the unmodifiedhttp.IncomingMessage object which may contain compressed data. See example below.
  • jar - iftrue, remember cookies for future use (or define your custom cookie jar; see examples section)

  • agent -http(s).Agent instance to use
  • agentClass - alternatively specify your agent's class name
  • agentOptions - and pass its options.Note: for HTTPS seetls API doc for TLS/SSL options and thedocumentation above.
  • forever - set totrue to use theforever-agentNote: Defaults tohttp(s).Agent({keepAlive:true}) in node 0.12+
  • pool - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool.Note:pool is used only when theagent option is not specified.
    • AmaxSockets property can also be provided on thepool object to set the max number of sockets for all agents created (ex:pool: {maxSockets: Infinity}).
    • Note that if you are sending multiple requests in a loop and creatingmultiple newpool objects,maxSockets will not work as intended. Towork around this, either userequest.defaultswith your pool options or create the pool object with themaxSocketsproperty outside of the loop.
  • timeout - integer containing number of milliseconds, controls two timeouts.
    • Read timeout: Time to wait for a server to send response headers (and start the response body) before aborting the request.
    • Connection timeout: Sets the socket to timeout aftertimeout milliseconds of inactivity. Note that increasing the timeout beyond the OS-wide TCP connection timeout will not have any effect (the default in Linux can be anywhere from 20-120 seconds)

  • localAddress - local interface to bind for network connections.
  • proxy - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for theurl parameter (by embedding the auth info in theuri)
  • strictSSL - iftrue, requires SSL certificates be valid.Note: to use your own certificate authority, you need to specify an agent that was created with that CA as an option.
  • tunnel - controls the behavior ofHTTPCONNECT tunnelingas follows:
    • undefined (default) -true if the destination ishttps,false otherwise
    • true - always tunnel to the destination by making aCONNECT request tothe proxy
    • false - request the destination as aGET request.
  • proxyHeaderWhiteList - a whitelist of headers to send to atunneling proxy.
  • proxyHeaderExclusiveList - a whitelist of headers to sendexclusively to a tunneling proxy and not to destination.

  • time - iftrue, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object:

    • elapsedTime Duration of the entire request/response in milliseconds (deprecated).
    • responseStartTime Timestamp when the response began (in Unix Epoch milliseconds) (deprecated).
    • timingStart Timestamp of the start of the request (in Unix Epoch milliseconds).
    • timings Contains event timestamps in millisecond resolution relative totimingStart. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
      • socket Relative timestamp when thehttp module'ssocket event fires. This happens when the socket is assigned to the request.
      • lookup Relative timestamp when thenet module'slookup event fires. This happens when the DNS has been resolved.
      • connect: Relative timestamp when thenet module'sconnect event fires. This happens when the server acknowledges the TCP connection.
      • response: Relative timestamp when thehttp module'sresponse event fires. This happens when the first bytes are received from the server.
      • end: Relative timestamp when the last bytes of the response are received.
    • timingPhases Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain:
      • wait: Duration of socket initialization (timings.socket)
      • dns: Duration of DNS lookup (timings.lookup -timings.socket)
      • tcp: Duration of TCP connection (timings.connect -timings.socket)
      • firstByte: Duration of HTTP server response (timings.response -timings.connect)
      • download: Duration of HTTP download (timings.end -timings.response)
      • total: Duration entire HTTP round-trip (timings.end)
  • har - aHAR 1.2 Request Object, will be processed from HAR format into options overwriting matching values(see theHAR 1.2 section for details)

  • callback - alternatively pass the request's callback in the options object

The callback argument gets 3 arguments:

  1. Anerror when applicable (usually fromhttp.ClientRequest object)
  2. Anhttp.IncomingMessage object (Response object)
  3. The third is theresponse body (String orBuffer, or JSON object if thejson option is supplied)

back to top


Convenience methods

There are also shorthand methods for different HTTP METHODs and some other conveniences.

request.defaults(options)

This methodreturns a wrapper around the normal request API that defaultsto whatever options you pass to it.

Note:request.defaults()does not modify the global request API;instead, itreturns a wrapper that has your default settings applied to it.

Note: You can call.defaults() on the wrapper that is returned fromrequest.defaults to add/override defaults that were previously defaulted.

For example:

//requests using baseRequest() will set the 'x-token' headerconstbaseRequest=request.defaults({headers:{'x-token':'my-token'}})//requests using specialRequest() will include the 'x-token' header set in//baseRequest and will also include the 'special' headerconstspecialRequest=baseRequest.defaults({headers:{special:'special value'}})

request.METHOD()

These HTTP method convenience functions act just likerequest() but with a default method already set for you:

  • request.get(): Defaults tomethod: "GET".
  • request.post(): Defaults tomethod: "POST".
  • request.put(): Defaults tomethod: "PUT".
  • request.patch(): Defaults tomethod: "PATCH".
  • request.del() / request.delete(): Defaults tomethod: "DELETE".
  • request.head(): Defaults tomethod: "HEAD".
  • request.options(): Defaults tomethod: "OPTIONS".

request.cookie()

Function that creates a new cookie.

request.cookie('key1=value1')

request.jar()

Function that creates a new cookie jar.

request.jar()

response.caseless.get('header-name')

Function that returns the specified response header field using acase-insensitive match

request('http://www.google.com',function(error,response,body){// print the Content-Type header even if the server returned it as 'content-type' (lowercase)console.log('Content-Type is:',response.caseless.get('Content-Type'));});

back to top


Debugging

There are at least three ways to debug the operation ofrequest:

  1. Launch the node process likeNODE_DEBUG=request node script.js(lib,request,otherlib works too).

  2. Setrequire('request').debug = true at any time (this does the same thingas #1).

  3. Use therequest-debug module toview request and response headers and bodies.

back to top


Timeouts

Most requests to external servers should have a timeout attached, in case theserver is not responding in a timely manner. Without a timeout, your code mayhave a socket open/consume resources for minutes or more.

There are two main types of timeouts:connection timeouts andreadtimeouts. A connect timeout occurs if the timeout is hit while your client isattempting to establish a connection to a remote machine (corresponding to theconnect() call on the socket). A read timeout occurs any time theserver is too slow to send back a part of the response.

These two situations have widely different implications for what went wrongwith the request, so it's useful to be able to distinguish them. You can detecttimeout errors by checkingerr.code for an 'ETIMEDOUT' value. Further, youcan detect whether the timeout was a connection timeout by checking if theerr.connect property is set totrue.

request.get('http://10.255.255.1',{timeout:1500},function(err){console.log(err.code==='ETIMEDOUT');// Set to `true` if the timeout was a connection timeout, `false` or// `undefined` otherwise.console.log(err.connect===true);process.exit(0);});

Examples:

constrequest=require('request'),rand=Math.floor(Math.random()*100000000).toString();request({method:'PUT',uri:'http://mikeal.iriscouch.com/testjs/'+rand,multipart:[{'content-type':'application/json',body:JSON.stringify({foo:'bar',_attachments:{'message.txt':{follows:true,length:18,'content_type':'text/plain'}}})},{body:'I am an attachment'}]},function(error,response,body){if(response.statusCode==201){console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+rand)}else{console.log('error: '+response.statusCode)console.log(body)}})

For backwards-compatibility, response compression is not supported by default.To accept gzip-compressed responses, set thegzip option totrue. Notethat the body data passed throughrequest is automatically decompressedwhile the response object is unmodified and will contain compressed data ifthe server sent a compressed response.

constrequest=require('request')request({method:'GET',uri:'http://www.google.com',gzip:true},function(error,response,body){// body is the decompressed response bodyconsole.log('server encoded the data as: '+(response.headers['content-encoding']||'identity'))console.log('the decoded data is: '+body)}).on('data',function(data){// decompressed data as it is receivedconsole.log('decoded chunk: '+data)}).on('response',function(response){// unmodified http.IncomingMessage objectresponse.on('data',function(data){// compressed data as it is receivedconsole.log('received '+data.length+' bytes of compressed data')})})

Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, setjar totrue (either indefaults oroptions).

constrequest=request.defaults({jar:true})request('http://www.google.com',function(){request('http://images.google.com')})

To use a custom cookie jar (instead ofrequest’s global cookie jar), setjar to an instance ofrequest.jar() (either indefaults oroptions)

constj=request.jar()constrequest=request.defaults({jar:j})request('http://www.google.com',function(){request('http://images.google.com')})

OR

constj=request.jar();constcookie=request.cookie('key1=value1');consturl='http://www.google.com';j.setCookie(cookie,url);request({url:url,jar:j},function(){request('http://images.google.com')})

To use a custom cookie store (such as aFileCookieStorewhich supports saving to and restoring from JSON files), pass it as a parametertorequest.jar():

constFileCookieStore=require('tough-cookie-filestore');// NOTE - currently the 'cookies.json' file must already exist!constj=request.jar(newFileCookieStore('cookies.json'));request=request.defaults({jar :j})request('http://www.google.com',function(){request('http://images.google.com')})

The cookie store must be atough-cookiestore and it must support synchronous operations; see theCookieStore API docsfor details.

To inspect your cookie jar after a request:

constj=request.jar()request({url:'http://www.google.com',jar:j},function(){constcookie_string=j.getCookieString(url);// "key1=value1; key2=value2; ..."constcookies=j.getCookies(url);// [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...]})

back to top

About

🏊🏾 Simplified HTTP request client.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript99.3%
  • Shell0.7%

[8]ページ先頭

©2009-2025 Movatter.jp