Giter VIP home page Giter VIP logo

sync-request's Introduction

sync-request

Make synchronous web requests with cross-platform support.

Requires at least node 8

N.B. You should not be using this in a production application. In a node.js application you will find that you are completely unable to scale your server. In a client application you will find that sync-request causes the app to hang/freeze. Synchronous web requests are the number one cause of browser crashes. For production apps, you should use then-request, which is exactly the same except that it is asynchronous.

Build Status Dependency Status NPM version

Installation

npm install sync-request

Usage

request(method, url, options);

e.g.

  • GET request without options
var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());
  • GET request with options
var request = require('sync-request');
var res = request('GET', 'https://example.com', {
  headers: {
    'user-agent': 'example-user-agent',
  },
});
console.log(res.getBody());
  • POST request to a JSON endpoint
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user', {
  json: {username: 'ForbesLindesay'},
});
var user = JSON.parse(res.getBody('utf8'));

Method:

An HTTP method (e.g. GET, POST, PUT, DELETE or HEAD). It is not case sensitive.

URL:

A url as a string (e.g. http://example.com). Relative URLs are allowed in the browser.

Options:

  • qs - an object containing querystring values to be appended to the uri
  • headers - http headers (default: {})
  • body - body for PATCH, POST and PUT requests. Must be a Buffer or String (only strings are accepted client side)
  • json - sets body but to JSON representation of value and adds Content-type: application/json. Does not have any affect on how the response is treated.
  • cache - Set this to 'file' to enable a local cache of content. A separate process is still spawned even for cache requests. This option is only used if running in node.js
  • followRedirects - defaults to true but can be explicitly set to false on node.js to prevent then-request following redirects automatically.
  • maxRedirects - sets the maximum number of redirects to follow before erroring on node.js (default: Infinity)
  • allowRedirectHeaders (default: null) - an array of headers allowed for redirects (none if null).
  • gzip - defaults to true but can be explicitly set to false on node.js to prevent then-request automatically supporting the gzip encoding on responses.
  • timeout (default: false) - times out if no response is returned within the given number of milliseconds.
  • socketTimeout (default: false) - calls req.setTimeout internally which causes the request to timeout if no new data is seen for the given number of milliseconds. This option is ignored in the browser.
  • retry (default: false) - retry GET requests. Set this to true to retry when the request errors or returns a status code greater than or equal to 400
  • retryDelay (default: 200) - the delay between retries in milliseconds
  • maxRetries (default: 5) - the number of times to retry before giving up.

These options are passed through to then-request, so any options that work for then-request should work for sync-request (with the exception of custom and memory caching strategies, and passing functions for handling retries).

Returns:

A Response object.

Note that even for status codes that represent an error, the request function will still return a response. You can call getBody if you want to error on invalid status codes. The response has the following properties:

  • statusCode - a number representing the HTTP status code
  • headers - http response headers
  • body - a string if in the browser or a buffer if on the server

It also has a method res.getBody(encoding?) which looks like:

function getBody(encoding) {
  if (this.statusCode >= 300) {
    var err = new Error(
      'Server responded with status code ' +
        this.statusCode +
        ':\n' +
        this.body.toString(encoding)
    );
    err.statusCode = this.statusCode;
    err.headers = this.headers;
    err.body = this.body;
    throw err;
  }
  return encoding ? this.body.toString(encoding) : this.body;
}

Common Problems

Could not use "nc", falling back to slower node.js method for sync requests.

If you are running on windows, or some unix systems, you may see the message above. It will not cause any problems, but will add an overhead of ~100ms to each request you make. If you want to speed up your requests, you will need to install an implementation of the nc unix utility. This usually done via something like:

apt-get install netcat

How is this possible?

Internally, this uses a separate worker process that is run using childProcess.spawnSync.

The worker then makes the actual request using then-request so this has almost exactly the same API as that.

This can also be used in a web browser via browserify because xhr has built in support for synchronous execution. Note that this is not recommended as it will be blocking.

License

MIT

sync-request's People

Contributors

dandv avatar danieljoppi avatar doublec avatar forbeslindesay avatar greenkeeper[bot] avatar icyflame avatar jongkeun avatar karelbilek avatar larsgw avatar micahzoltu avatar ribalba avatar vzaharee avatar wisq 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

sync-request's Issues

how to upload?

i can't upload file...

    var resData,
        results;

    // 设置基本参数
    var options = {
        'headers':{
            'Content-Type':'multipart/form-data',
            'Accept-Encoding': 'multipart/form-data'
        },
        'file':fsdo.createReadStream(file_path),
        'body':'taskid='+taskid, // 参数
        'timeout': conf.rep_timeout, // 返回超时
        'socketTimeout': conf.req_timeout // 请求超时
    }

    // 异常包含
    try {
        // 请求过程、返回
        resData = request('POST',upload_url_path,options);
        if (resData.statusCode == 200){
            results = ''+ resData.getBody('utf8');
            console.log(resData.headers);
        }else{
            log.reqError(interFace,resData.statusCode,'POST request Status is not Fine!!');
        }
    } catch(e) {
        // 异常处理的地方
        log.reqPackageError(interFace,upload_url_path,e.stack);
    }
    return results;

Jsonp

Is it possible, to make jsonp request? I have to make request to another domain.

followRedirects doesn't take effect on http redirect 302

Server responded with status code 302 to another URL

But it doesn't redirect as it should.

The process just stops at synrequest.

No error and no response forever.

                    try {
                        res = synrequest("GET", url, {
                            rejectUnauthorized: false,
                            timeout: false,
                            headers: headers,
                            followRedirects: true,
                            maxRedirects: 2,
                            socketTimeout: 5000
                        });
                    } catch (e) {
                        console.log(e);
                    }

CERT_UNTRUSTED

I am getting CERT_UNTRUSTED from an https URL.
Is there an (undocumented?) option to skip the certificate check?

Blocks Node Process

While using Sync Request for uploading CSV files, blocks the process. Is anything can be done to solve this ?

Nativee thread-sleep not available.

How do you disable this message?

Native thread-sleep not available.
This will result in much slower performance.
You should re-install spawn-sync if possible.

Better documentation for options

It would be great to have more info about the options and how to use them.

I assumed the json option can be set to true and I tried

var request = require('sync-request');
var res = request('GET', 'http://example.com', {'json': true});
console.log(res);

but the json:true doesn't work for me. Maybe the current documentation can be improved:

json - sets body but to JSON representation of value and adds Content-type: application/json.
Does not have any affect on how the response is treated.

Error: The method must be a string.

works fine in a standalone module, but inside an express I have this:

/usr/bin/node /home/in/MyDomoAtHome-nodejs/mdah.js
/home/in/MyDomoAtHome-nodejs/node_modules/sync-request/index.js:37
throw new Error(response.error.message || response.error || response);
^

Error: The method must be a string.
at doRequest (/home/in/MyDomoAtHome-nodejs/node_modules/sync-request/index.js:37:11)
at getLastVersion (/home/in/MyDomoAtHome-nodejs/mdah.js:69:9)
at Object. (/home/in/MyDomoAtHome-nodejs/mdah.js:40:19)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:140:18)
at node.js:1001:3

Process finished with exit code 1

in windows,it's ok.in mac it's error

in windows it's ok

var request = require('sync-request');
var res = request('GET', 'http://www.google.com');
console.log(res.getBody());

in mac it's error

TypeError: invalid data
    at WriteStream.Socket.write (net.js:609:11)
    at doRequest (/Users/Mac/code/client/node_modules/sync-request/index.js:21:20)

Error: connect ETIMEDOUT

The connection somehow times out and causes an error that causes an exception that crashes. Not sure if you can make this more graceful.

/opt/node/node_modules/sync-request/index.js:31
throw new Error(response.error.message || response.error || response);
^
Error: connect ETIMEDOUT
at doRequest (/opt/nodeNexia/node_modules/sync-request/index.js:31:11)
.....
at Socket.EventEmitter.emit (events.js:98:17)
at UDP.onMessage (dgram.js:423:8)

http://stackoverflow.com/questions/23632914/how-to-handle-etimedout-error

making post with multipart/form content-type

What is the correct way to set the headers/body to be able to make a post request with a multipart/form content-type? I can't figure out where these should go (or where to put them):

----Z7depKeH0iSSjand
Content-Disposition: form-data; name="file"; filename="test.csv"
Content-Type: text/csv

----Z7depKeH0iSSjand
Content-Disposition: form-data; name="filename"

test.csv
----Z7depKeH0iSSjand

This is what I currently have:

    const csv = makeRequest(); // does a GET, stores the csv from that response into a buffer 
    const opts = {
      headers: {
        'Content-Type': 'multipart/form-data; boundary=----Z7depKeH0iSSjand',
        'Accept-Encoding': 'multipart/form-data',
        'X-AUTH-TOKEN': authToken,
      },
      body: csv,
    }
    request('POST', url, opts)

New method to enable stubbing

Hi

Love the library, I've got a valid use for it but....It's hard to test. It's fallen into the same syntax trap as 'request', namely the lack of a function to stub on.

You can see people discussing it about request here - http://stackoverflow.com/questions/20050507/creating-request-stub-with-sinon-in-mocha

Request does have 'get' and 'post' to enable stubbing. Could we get the same on this library? It would be most helpful

Or if I could get in contact with someone, I feel like the change itself would not be overly difficult but talking through it would be great.

request failing after a while.

Hi , i use this module in my web scraper and it works fine for a while but then all requests start failing,
i first thought it may be that the host is blocking but i tried and i could still access the same url that is failing with sync-request. hear is the error i get:
TypeError: Cannot read property 'toString' of null at doRequest (/home/ubuntu/testdir/tvguide/node_modules/sync-request/index.js:27:31)

Basic GET request is sending Content-Length header

Hi,

I am trying to replace a normal request with a sync-request, however when I try to retrieve the body of a URL, the webserver is rejecting it due to 'Content-Length: 0' being in the header

GET /uploaded_files/holidayCalendar.ics HTTP/1.1
Content-Length: 0
Host: www.safework.sa.gov.au
Connection: close

Without the Content-Length being defined the server is happy to send a response, however with it in the request, it see it as malformed and drops the request

Andrew

POST on redirect

After about 3 hours of looking through the code of all the dependencies and this package I couldn't find a way to do POST requests on redirected pages. The issue seems to be on the fact that the req.end(body) is called on the first request and there is no way of calling it on the second (produced in http-basic).
Also, this library does not allow for configuration of the following of redirects, as then-request sets it to true as default and does not allow for manipulation.

Other than this, thanks so much for the work on the libraries!

Cheers.

Timeout option

Sync request should have an option for timeout so it doesn't get stuck for that long

Error for DELETE

Hi,

We get "Socket hangup" as error while trying to execute the below code

var res = syncRequest('DELETE', global.packageData.configurationServiceUrl + 'deleteConfig', {
        json: { data: configElement }
    });
    return JSON.parse(res.getBody('utf8'));

If we pass null for the bodyContent parameter it works fine. Like below:

var res = syncRequest('DELETE', global.packageData.configurationServiceUrl + 'deleteConfig', null);
    return JSON.parse(res.getBody('utf8'));

Can you suggest the solution to this?

Recommended spawn-sync version does not exist

Using Node.js 0.10.29, sync-request aborts with the error below.

     Error: Sync-request requires node version 0.12 or later.  If you need to use it with an older version of node
you can `npm install [email protected]`, which was the last version to support older versions of node.
      at doRequest (node_modules/sync-request/index.js:15:11)
      at Object.checkBarcode (index.js:30:15)
      at Context.<anonymous> (test/index.js:6:18)

Trying to install spawn-sync 2.2.0 does fail though. According to the README the latest version is 1.0.15.

certificate has expired

I'm trying to use sync-request to get rest api resources from a custom-build embedded device. This device's http server uses ssl/https with an expired certificate. For reasons that are both complicated and boring we're not going to bother trying to update the certificate.

Is there some way to configure sync-request to ignore expired certificates? Something like curl's -k option or wget's --no-check-certificate option?

Issue with v2.0.0

There seems to be a bit of an issue with 2.0.0, or maybe it's just me.

image

I'm using v0.12.0 of node.js, but the same thing happens on v0.10.36.

POST request is not working.. body only contains true

I tried on this code even with JSON.stringify on my data, and tried
to combine with using and not using option json: true options but it doesn't work.
I've check output request on http://www.posttestserver.com/ , the body contains only 4 letters of 'true'

var result = request('POST', testUrl, {
    data : {
      key: publicKey.toString(),
      info: {
        clientName: 'GG',
        adapterUrl: 'https://localhost:3000'
      },
    json: true
  });

Application freezes when passing 'json' parameter into a 'GET' request

Hello!
First of all let me thank you for publishing this library, it is helping us to make some internal-use and testing scripts, that we write using NodeJS.

We observed that if configuration object of a "GET" request includes the "json" property, the script freezes (The script does not resume its work never) and does not shows any error message.

It would be great if the library showed an error or a warning every time this happens, for making code debugging easier.

http basic auth

i was just wondering if this lib supported http basic auth, as i didn't see anything in the documentation

Proxy settings...

Hello, not sure if this feature is already there, but I'm having problems trying to make a request behind a proxy. I couldn't find any documentation about that.

how to get response cookie ??

{ server: 'nginx/1.10.1',
date: 'Fri, 07 Oct 2016 11:05:18 GMT',
'content-type': 'text/html',
'transfer-encoding': 'chunked',
connection: 'close',
'x-powered-by': 'PHP/5.5.31',
'set-cookie':
[ 'ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22cfd30f3790c9c54a3a37d59a31e964a3%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A9%3A%22127.0.0.1%22%3Bs%3A10%3A%22user_agent%22%3Bb%3A0%3Bs%3A13%3A%22last_activity%22%3Bi%3A1475838318%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D0bd06711d12f305a41296c637a0d670c510dcf07; expires=Fri, 07-Oct-2016 13:05:18 GMT; Max-Age=7200; path=/',
'ci_session=a%3A6%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22cfd30f3790c9c54a3a37d59a31e964a3%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A9%3A%22127.0.0.1%22%3Bs%3A10%3A%22user_agent%22%3Bb%3A0%3Bs%3A13%3A%22last_activity%22%3Bi%3A1475838318%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3Bs%3A8%3A%22username%22%3Bb%3A0%3B%7D86252f436517ca9d65c812f9ebee93ea137123b6; expires=Fri, 07-Oct-2016 13:05:18 GMT; Max-Age=7200; path=/' ] }

response have "set-cookie", I login in for php and have a session,than, I want get cookie.how can i get response cookie?

Too many open sockets if multiple http calls are made at a time

I'm writing a custom module and using sync-request where it opens 5 sockets at a time. I got the below error which suggests me that there are too many open sockets.

child_process.js:948

    throw errnoException(process._errno, 'spawn');
          ^

Error: spawn EMFILE

    at errnoException (child_process.js:1001:11)

    at ChildProcess.spawn (child_process.js:948:11)

    at exports.spawn (child_process.js:736:9)

    at Object.exports.execFile (child_process.js:618:15)

    at Object.exports.exec (child_process.js:589:18)

    at invoke (/home/postman/es-data-migrator/node_modules/sync-request/node_modules/spawn-sync/lib/spawn-sync.js:57:6)

    at spawnSyncFallback (/home/postman/es-data-migrator/node_modules/sync-request/node_modules/spawn-sync/lib/spawn-sync.js:84:3)

    at doRequest (/home/postman/es-data-migrator/node_modules/sync-request/index.js:19:13)

    at esdm.getData (/home/postman/es-data-migrator/src/lib/esdm.lib.js:20:27)

Update README to remove `spawn-sync` dependency

In the readme it says that this depends on a compiled package spawn-sync.
First I was going to fork this repo and remove that dependency, but then I found out that there's no spawn-sync dependency.
You can update the README accordingly.
Original:

Internally, this uses a separate worker process that is run using either [childProcess.spawnSync](http://nodejs.org/docs/v0.11.13/api/child_process.html#child_process_child_process_spawnsync_command_args_options) if available, or falling back to [spawn-sync](https://www.npmjs.org/package/spawn-sync) if not.  The fallback will attempt to install a native module for synchronous execution, and fall back to doing busy waiting for a file to exist.  All this ultimatley means that the module is totally cross platform and does not require native code compilation support.

Failed to install under node 5.1.0

CXX(target) Release/obj.target/curllib/curllib.o
../curllib.cc:26:17: error: expected class name
class CurlLib : ObjectWrap {
                ^
../curllib.cc:59:34: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
  static Handle<Value> New(const Arguments& args) {
                                 ^~~~~~~~~
                                 v8::internal::Arguments
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:139:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../curllib.cc:92:35: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
  static Handle<Value> Body(const Arguments& args) {
                                  ^~~~~~~~~
                                  v8::internal::Arguments
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:139:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../curllib.cc:114:34: error: unknown type name 'Arguments'; did you mean 'v8::internal::Arguments'?
  static Handle<Value> Run(const Arguments& args) {
                                 ^~~~~~~~~
                                 v8::internal::Arguments
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:139:7: note: 'v8::internal::Arguments' declared here
class Arguments;
      ^
../curllib.cc:38:55: error: cannot initialize a parameter of type 'v8::Isolate *' with an lvalue of type 'Handle<v8::Value>
      (const v8::internal::Arguments &)'
    Local<FunctionTemplate> t = FunctionTemplate::New(New);
                                                      ^~~
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:4349:16: note: passing argument to parameter 'isolate' here
      Isolate* isolate, FunctionCallback callback = 0,
               ^
../curllib.cc:40:42: error: 'New' is a private member of 'v8::PersistentBase<v8::FunctionTemplate>'
    s_ct = Persistent<FunctionTemplate>::New(t);
                                         ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:643:23: note: declared private here
  V8_INLINE static T* New(Isolate* isolate, T* that);
                      ^
../curllib.cc:40:12: error: too few arguments to function call, expected 2, have 1; did you mean '::CurlLib::New'?
    s_ct = Persistent<FunctionTemplate>::New(t);
           ^~~~~~~~~~
           ::CurlLib::New
../curllib.cc:59:24: note: '::CurlLib::New' declared here
  static Handle<Value> New(const Arguments& args) {
                       ^
../curllib.cc:41:9: error: member reference type 'Persistent<v8::FunctionTemplate>' is not a pointer; maybe you meant to use '.'?
    s_ct->InstanceTemplate()->SetInternalFieldCount(1);
    ~~~~^~
        .
../curllib.cc:41:11: error: no member named 'InstanceTemplate' in 'v8::Persistent<v8::FunctionTemplate,
      v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >'
    s_ct->InstanceTemplate()->SetInternalFieldCount(1);
    ~~~~  ^
../curllib.cc:42:9: error: member reference type 'Persistent<v8::FunctionTemplate>' is not a pointer; maybe you meant to use '.'?
    s_ct->SetClassName(String::NewSymbol("CurlLib"));
    ~~~~^~
        .
../curllib.cc:42:11: error: no member named 'SetClassName' in 'v8::Persistent<v8::FunctionTemplate,
      v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >'
    s_ct->SetClassName(String::NewSymbol("CurlLib"));
    ~~~~  ^
../curllib.cc:42:32: error: no member named 'NewSymbol' in 'v8::String'
    s_ct->SetClassName(String::NewSymbol("CurlLib"));
                       ~~~~~~~~^
../curllib.cc:44:31: error: no viable conversion from 'Persistent<v8::FunctionTemplate>' to 'v8::Local<v8::FunctionTemplate>'
    NODE_SET_PROTOTYPE_METHOD(s_ct, "run", Run);
                              ^~~~
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:210:7: note: candidate constructor (the implicit copy constructor) not viable: no known
      conversion from 'Persistent<v8::FunctionTemplate>' to 'const v8::Local<v8::FunctionTemplate> &' for 1st argument
class Local {
      ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:210:7: note: candidate constructor (the implicit move constructor) not viable: no known
      conversion from 'Persistent<v8::FunctionTemplate>' to 'v8::Local<v8::FunctionTemplate> &&' for 1st argument
class Local {
      ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:214:13: note: candidate template ignored: could not match 'Local' against 'Persistent'
  V8_INLINE Local(Local<S> that)
            ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:326:13: note: candidate template ignored: could not match 'S *' against
      'Persistent<v8::FunctionTemplate>'
  V8_INLINE Local(S* that)
            ^
/Users/marktyers/.node-gyp/5.1.0/include/node/node.h:252:71: note: passing argument to parameter 'recv' here
inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
                                                                      ^
../curllib.cc:45:31: error: no viable conversion from 'Persistent<v8::FunctionTemplate>' to 'v8::Local<v8::FunctionTemplate>'
    NODE_SET_PROTOTYPE_METHOD(s_ct, "body", Body);
                              ^~~~
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:210:7: note: candidate constructor (the implicit copy constructor) not viable: no known
      conversion from 'Persistent<v8::FunctionTemplate>' to 'const v8::Local<v8::FunctionTemplate> &' for 1st argument
class Local {
      ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:210:7: note: candidate constructor (the implicit move constructor) not viable: no known
      conversion from 'Persistent<v8::FunctionTemplate>' to 'v8::Local<v8::FunctionTemplate> &&' for 1st argument
class Local {
      ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:214:13: note: candidate template ignored: could not match 'Local' against 'Persistent'
  V8_INLINE Local(Local<S> that)
            ^
/Users/marktyers/.node-gyp/5.1.0/include/node/v8.h:326:13: note: candidate template ignored: could not match 'S *' against
      'Persistent<v8::FunctionTemplate>'
  V8_INLINE Local(S* that)
            ^
/Users/marktyers/.node-gyp/5.1.0/include/node/node.h:252:71: note: passing argument to parameter 'recv' here
inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
                                                                      ^
../curllib.cc:48:21: error: member reference type 'Persistent<v8::FunctionTemplate>' is not a pointer; maybe you meant to use '.'?
                s_ct->GetFunction());
                ~~~~^~
                    .
../curllib.cc:48:23: error: no member named 'GetFunction' in 'v8::Persistent<v8::FunctionTemplate,
      v8::NonCopyablePersistentTraits<v8::FunctionTemplate> >'
                s_ct->GetFunction());
                ~~~~  ^
../curllib.cc:47:25: error: no member named 'NewSymbol' in 'v8::String'
    target->Set(String::NewSymbol("CurlLib"),
                ~~~~~~~~^
../curllib.cc:50:23: error: use of undeclared identifier 'NODE_PSYMBOL'
    sym_body_length = NODE_PSYMBOL("body_length");
                      ^
../curllib.cc:51:19: error: use of undeclared identifier 'NODE_PSYMBOL'
    sym_headers = NODE_PSYMBOL("headers");
                  ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/curllib/curllib.o] Error 1
gyp ERR! build error 
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/marktyers/.nvm/versions/node/v5.1.0/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 15.0.0
gyp ERR! command "/Users/marktyers/.nvm/versions/node/v5.1.0/bin/node" "/Users/marktyers/.nvm/versions/node/v5.1.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/marktyers/Documents/305CDE/labs/03 Asynchronous JavaScript/node_modules/http-sync
gyp ERR! node -v v5.1.0
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok 
npm WARN install:[email protected] [email protected] install: `node-gyp rebuild`
npm WARN install:[email protected] Exit status 1

Request: Have sync-request work with web workers

I love sync-request! Anyway to have it work with web-workers and function the same while receiving the web worker performance boost?

I been using it in my riotapi project and it's wonderful, just on the frontend, it does the usual freezes due to the nature of xhr sync request.

If you wanted to see how I was using it.
https://github.com/JemiloII/riotapi/blob/master/riotapi/champion/champion.js

var Lux = champion('Lux'); // makes request and now is json data :)

sync-request is making code run too slow

While running sync-request for scrapping web pages in 'for' loop, it is taking hell lot of time for each iteration/request. If I use default async request socket hangs up.
At start of execution sync-request consoles "native module could not be found so busy waiting will be used for spwan-sync"

Probably caching error: ENOENT, no such file or directory Error: ENOENT, no such file or directory '/var/folders/...'

Hello, Sir

Unfortunately I keep getting this error when I am using sync-request in my project.

Environment:
$ node -v
v0.10.36
$ uname -a
Darwin host.some.domain 14.3.0 Darwin Kernel Version 14.3.0: Mon Mar 23 11:59:05 PDT 2015; root:xnu-2782.20.48~5/RELEASE_X86_64 x86_64
$

Parameters to the request:
...
var resourceUrl = util.format(baseUrl, querystring.escape(id));
var options = {
gzip: false,
headers: {
'some-header': 'some-value'
}
};
var res = request('GET', resourceUrl, options);
...

This is a straight REST-call with an identifier in the URL,-and the identifier is URL-encoded (as you can see).

fs.js:439
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^
Error: ENOENT, no such file or directory '/var/folders/mn/yl6t62f949g6q6ly5b2sk9880000gn/T/spawn-sync_output_28876a1c1303314dc4322934d'
at Object.fs.openSync (fs.js:439:18)
at Object.fs.readFileSync (fs.js:290:15)
at spawnSyncFallback (/Users/kandal/tmp/git/vendor-integration/node_modules/sync-request/node_modules/spawn-sync/lib/spawn-sync.js:86:27)
at doRequest (/some/path/node_modules/sync-request/index.js:19:13)

(The name for the temporary file is of course different each time)
Thank You very much.

Trond.

Unkown Request Error

sync-request/index.js:31
throw new Error(response.error.message || response.error || response);
^
Error: The protocol "null" is not supported, cannot load ""
at doRequest (/sync-request/index.js:31:11)
at Object. (/start.js:227:28)

Issue with SSL

I'm trying to use sync-request on a URL that has SSL enabled and I'm getting the following error: Error: unable to verify the first certificate

Has anyone else ran into this?

The way to upload file

Hi ,

I am trying to upload file using sync-request.
Here is my way of uploading(using data as the Buffer to upload)

var fs = require('fs');
fs.readFile('to-upload/test.txt', function (err, data) {
    if (err) throw err;
        var resUploadFile = syncRequest('PUT', uploadUrl, {
            data: data
        });
   log(JSON.parse(resUploadFile.statusCode));
});

However I failed to upload the file in this way. Can you tell me what's the correct way of uploading files using sync-request.

Thanks!

Pass through the final URL in the Response

then-request returns the final URL:

url - the URL that was requested (in the case of redirects on the server, this is the final url that was requested)

Would be great if sync-request passed that along. Right now, res.url returns undefined.

getBody return Buffer instead of string when no encoding present

Hello,

response.getBody() throws the next error when no encoding is present.
AssertionError: expected <Buffer 5b 7b 22 ...

Seeing node Buffer toString method:
# encoding String, Optional, Default: 'utf8'

Maybe return this.body.toString() (with utf8 by default) instead of this.body will fix this?

Regards

Json option in request is not resolving variable reference.

I have a Json String saved to a variable jsonString, If i refernce that variable in req object it is not getting resolved. It would be of great help if you can sort out this.

var res = syncRequest('POST', url,
{
json: jsonString
},{
'headers': {
'content-type': 'application/json',
'Authorization':'Basic ****',
}
});

Error: Parse Error

I am trying to create a Node client module for an HTTP server using sync-reqeust because I (think I) need to make the request synchronously. However, I don't get it to run.

I tracked it down to to the

  var response = JSON.parse(res.stdout);
  if (response.success) {

clause in sync-request's index.js file.
Printing response in the else clause returns

{ success: false, error: { message: 'Parse Error' } }

The request must be composed properly, as the server (which is written in Python using HTTPBaseRequestHandler) parses it properly and produces the right response.

According to the output in Firefox's HttpRequester extension the complete "raw transaction" looks like this:

POST http://localhost:5432
Content-Type: application/json

 -- response --
200 OK

{
    "info": [
        {
            "info": "lilypond",
            "command": "mode"
        },
        {
            "info": "",
            "command": "version"
        }
    ],
    "doc": {
        "commands": [
            "transpose",
            "reformat"
        ],
        "content": "%No JSON data supplied. This is a test request.\n\\relative c' {\n  d4 ( e fis )\n}"
    },
    "exports": [
        {
            "command": "highlight",
            "doc": "<pre class=\"lilypond\"><span class=\"lilypond-comment comment\">%No JSON data supplied. This is a test request.\n</span><span class=\"lilypond-command function\">\\relative</span> <span class=\"lilypond-pitch\">c</span><span class=\"lilypond-octave\">'</span> <span class=\"lilypond-delimiter keyword\">{\n  </span><span class=\"lilypond-pitch\">d</span><span class=\"lilypond-duration\">4</span> <span class=\"lilypond-slur\">(</span> <span class=\"lilypond-pitch\">e fis</span> <span class=\"lilypond-slur\">)\n</span><span class=\"lilypond-delimiter keyword\">}</span></pre>"
        }
    ]
}HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.4.2
Date: Wed, 13 Apr 2016 10:16:53 GMT
Content-type: application/json

I don't know why the headers are printed here after the response body, I used HTTPBaseRequestHandlers's methods in the following order:

self.send_response(200)
self.send_header('Content-type', 'application/json')
self.wfile.write(res_body)
self.end_headers()

I don't know if there's anything wrong with the HTTP response, or if I have to do something special to accept the JSON object as the response body.

The function starting the request looks like this:

exec_server: function(options, command, doc) {

    try {
        var res = request('POST', 'http://localhost:5432', {
            json: {
                // The JSON object to send
            }
        });
    }
    catch (e){
        console.log(e);
        return "";
    };
    return res.body.toString();

Any help or clarification would be appreciated!

GET with request body times out

request('GET', 'http://requestb.in/1lhfdlb1', {
  'json': {
    'a': 'b',
  },
});

times out for me. (generate a new requestbin url to test)

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.