Javascript sync post request

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Make synchronous web requests with cross platform support.

License

ForbesLindesay/sync-request

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Make synchronous web requests with cross-platform support.

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.

request(method, url, options);
var request = require('sync-request'); var res = request('GET', 'http://example.com'); console.log(res.getBody());
var request = require('sync-request'); var res = request('GET', 'https://example.com',  headers:  'user-agent': 'example-user-agent', >, >); console.log(res.getBody());
var request = require('sync-request'); var res = request('POST', 'https://example.com/create-user',  json: username: 'ForbesLindesay'>, >); var user = JSON.parse(res.getBody('utf8'));

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

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

  • 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).

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; >

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:

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.

Источник

POST JSON Data by sync-request module (Node.js)

Testing of POST with sync-request which can execute HTTP GET by synchronous processing.

In this article, since it is asynchronous with the requst module of Node.js (JavaScript), I introduced the srnc-request module which can synchronize without callback function.

Node.js source code

Source code is here. The points will be described later.

npm information

Command syntax for posting JSON officially is stated. This time I make information to POST with variables.

var request = require('sync-request'); var res = request('POST', 'https://example.com/create-user', < json: < username: 'ForbesLindesay' >>); var user = JSON.parse(res.getBody('utf8'));

Items that can be used in the Options section are prescribed. In this time, instead of adding «Content-type: application/json» to the Header, I used json already defined.

POST JSON to Redmine API and create a ticket

I have referred to here about POST of Redmine API. Thank you very much.

As a point JSON at ticket registration has a different syntax from GET. It is necessary to specify various items with «\_id».

function redminePost() bodyJson = «issue»: «project_id»:13, // NG!! «project»:, «tracker_id»:1, «status_id»:1,

The POST part is here. Since json contains Content-type, Header is not necessary.

var response = request( 'POST', 'http://'+ticketUrl+'/issues.json?key='+ticketKey, // no need //headers: headerJson, json: bodyJson >);

Execution result

When the above source code is executed, the result is returned as follows.

Response code is 201, header / body contains various kinds of information and created ticket information.

Start Response < statusCode: 201, headers: < date: 'Sat, 19 Nov 2016 07:15:20 GMT', server: 'Apache/2.4.6 (CentOS) PHP/5.4.16 Phusion_Passenger/5.0.21', 'cache-control': 'max-age=0, private, must-revalidate', 'x-frame-options': 'SAMEORIGIN', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'x-request-id': '1c51e2d8-9f5e-44c2-b107-884a04a06d21', location: 'http:///issues/', etag: 'W/"39d9d5ced85e556ab368c6065c935908"', 'content-length': '508', status: '201 Created', connection: 'close', 'content-type': 'application/json; charset=utf-8' >, body: , url: undefined > body < issue: < id: 116, project: < id: 13, name: 'WebSystem' >, tracker: < id: 3, name: 'Support' >, status: < id: 1, name: 'New' >, priority: < id: 2, name: 'Normal' >, author: < id: 5, name: '' >, subject: 'Cannot POST JSON Data bt Node.js', description: '', start_date: '2016-11-19', done_ratio: 0, custom_fields: [ [Object], [Object] ], created_on: '2016-11-19T07:15:20Z', updated_on: '2016-11-19T07:15:20Z' > > End

Conclusion — POST JSON Data by sync-request module (Node.js)

I was able to POST by sync process with sync-request. Without using callback functions and so on, it is possible to simply perform ordered processing with Node.js (JavaScript).

Источник

Javascript sync post request

Make synchronous web requests with cross-platform support.

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.

request(method, url, options);
var request = require('sync-request');
var res = request('GET', 'http://example.com');
console.log(res.getBody());
var request = require('sync-request');
var res = request('GET', 'https://example.com',
headers:
'user-agent': 'example-user-agent',
>,
>);
console.log(res.getBody());
var request = require('sync-request');
var res = request('POST', 'https://example.com/create-user',
json: username: 'ForbesLindesay'>,
>);
var user = JSON.parse(res.getBody('utf8'));

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

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

  • 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).

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;
>

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:

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.

Источник

Читайте также:  Php parameter data type
Оцените статью