Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
then-request
Advanced tools
The then-request npm package is a simplified HTTP client for Node.js that uses promises. It allows you to make HTTP requests and handle responses in a straightforward manner using promises, making it easier to work with asynchronous code.
Basic GET Request
This feature allows you to make a basic GET request to a specified URL. The response is handled using a promise, and the response body is logged to the console.
const request = require('then-request');
request('GET', 'https://jsonplaceholder.typicode.com/posts/1')
.done(function (res) {
console.log(res.getBody());
});
POST Request with JSON Body
This feature allows you to make a POST request with a JSON body. The request sends data to the specified URL, and the response is handled using a promise.
const request = require('then-request');
request('POST', 'https://jsonplaceholder.typicode.com/posts', {
json: {
title: 'foo',
body: 'bar',
userId: 1
}
}).done(function (res) {
console.log(res.getBody());
});
Handling Response Headers
This feature allows you to access and log the response headers from an HTTP request. The headers are available in the response object.
const request = require('then-request');
request('GET', 'https://jsonplaceholder.typicode.com/posts/1')
.done(function (res) {
console.log(res.headers);
});
Handling Errors
This feature demonstrates how to handle errors in HTTP requests. If the request fails, the error is caught and logged to the console.
const request = require('then-request');
request('GET', 'https://jsonplaceholder.typicode.com/invalid-url')
.done(function (res) {
console.log(res.getBody());
}, function (err) {
console.error('Request failed:', err);
});
Axios is a popular promise-based HTTP client for Node.js and the browser. It provides a more feature-rich API compared to then-request, including support for interceptors, request cancellation, and automatic JSON transformation.
Node-fetch is a lightweight module that brings the Fetch API to Node.js. It is similar to then-request in that it uses promises, but it follows the Fetch API standard, making it a good choice for those familiar with the browser's Fetch API.
Request-promise is a simplified HTTP client that extends the request library with promise support. It offers a more extensive set of features compared to then-request, including support for various authentication methods and multipart form data.
A request library that returns promises, inspired by request
npm install then-request
request(method, url, options, callback?)
e.g.
var request = require('then-request');
request('GET', 'http://example.com').done(function (res) {
console.log(res.getBody());
});
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 uriheaders
- 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
- only used in node.js (browsers already have their own caches) Can be 'memory'
, 'file'
or your own custom implementaton (see https://github.com/ForbesLindesay/http-basic#implementing-a-cache).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
)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 (can also be a function that takes (err, req, attemptNo) => shouldRetry
)retryDelay
(default: 200
) - the delay between retries (can also be set to a function that takes (err, res, attemptNo) => delay
)maxRetries
(default: 5
) - the number of times to retry before giving up.Callback / Returns:
If a callback is provided it is called with err
and res
. If no callback is provided, a Promise is returned that eventually resolves to res
. The resulting Promise also has an additional .getBody(encoding?)
method that is equivallent to calling .then(function (res) { return res.getBody(encoding?); })
.
Note that even for status codes that represent an error, the promise will be resolved as the request succeeded. 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 codeheaders
- http response headersbody
- a string if in the browser or a buffer if on the serverurl
- the URL that was requested (in the case of redirects on the server, this is the final url that was requested)It also has a method 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;
}
MIT
FAQs
A request library that returns promises, inspired by request
The npm package then-request receives a total of 878,565 weekly downloads. As such, then-request popularity was classified as popular.
We found that then-request demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.