Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Popsicle is a versatile HTTP request library for Node.js and the browser. It provides a simple and consistent API for making HTTP requests, handling responses, and managing various aspects of HTTP communication such as headers, query parameters, and request/response bodies.
Making HTTP Requests
This feature allows you to make HTTP requests to a specified URL. The example demonstrates a GET request to a JSON placeholder API, logging the status and body of the response.
const { request } = require('popsicle');
request('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.status);
console.log(response.body);
})
.catch(error => {
console.error(error);
});
Handling Query Parameters
This feature allows you to include query parameters in your HTTP requests. The example demonstrates a GET request with a query parameter to filter posts by userId.
const { request } = require('popsicle');
request({
url: 'https://jsonplaceholder.typicode.com/posts',
query: { userId: 1 }
})
.then(response => {
console.log(response.status);
console.log(response.body);
})
.catch(error => {
console.error(error);
});
Setting Headers
This feature allows you to set custom headers for your HTTP requests. The example demonstrates setting the 'Content-Type' header to 'application/json'.
const { request } = require('popsicle');
request({
url: 'https://jsonplaceholder.typicode.com/posts',
headers: { 'Content-Type': 'application/json' }
})
.then(response => {
console.log(response.status);
console.log(response.body);
})
.catch(error => {
console.error(error);
});
Handling Request and Response Bodies
This feature allows you to handle request and response bodies. The example demonstrates a POST request with a JSON body to create a new post.
const { request } = require('popsicle');
request({
method: 'POST',
url: 'https://jsonplaceholder.typicode.com/posts',
body: { title: 'foo', body: 'bar', userId: 1 },
headers: { 'Content-Type': 'application/json' }
})
.then(response => {
console.log(response.status);
console.log(response.body);
})
.catch(error => {
console.error(error);
});
Axios is a popular promise-based HTTP client for the browser and Node.js. It provides a simple API for making HTTP requests and handling responses, similar to Popsicle. Axios is known for its ease of use and wide adoption in the JavaScript community.
Node-fetch is a lightweight module that brings `window.fetch` to Node.js. It is a minimalistic library that provides a simple API for making HTTP requests, similar to the Fetch API in the browser. Node-fetch is often used for its simplicity and compatibility with the Fetch API standard.
Superagent is a small progressive client-side HTTP request library, and Node.js module with a similar API. It provides a flexible and powerful API for making HTTP requests and handling responses. Superagent is known for its extensive feature set and ease of use.
Popsicle is designed to be easiest way for making HTTP requests, offering a consistent and intuitive API that works on both node and the browser.
popsicle('/users.json')
.then(function (res) {
console.log(res.body) //=> { ... }
})
npm install popsicle --save
bower install popsicle --save
You will need a promise polyfill for older browsers and node <= 0.11.12
.
npm install es6-promise --save
bower install es6-promise --save
Apply the polyfill.
// Node and browserify
require('es6-promise').polyfill()
// Browsers
window.ES6Promise.polyfill()
var popsicle = require('popsicle')
// var popsicle = window.popsicle
popsicle({
method: 'POST',
url: 'http://example.com/api/users',
body: {
username: 'blakeembrey',
password: 'hunter2'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (res) {
console.log(res.status) // => 200
console.log(res.body) //=> { ... }
console.log(res.get('Content-Type')) //=> 'application/json'
})
"GET"
){}
)Infinity
)true
)Node only
null
)10
)true
)false
)Browser only
false
)Popsicle can automatically serialize the request body to a string. If an object is supplied, it'll automatically stringify as JSON unless the Content-Type
header was set otherwise. If the Content-Type
is multipart/form-data
or application/x-www-form-urlencoded
, it can also be automatically serialized.
popsicle({
url: 'http://example.com/api/users',
body: {
username: 'blakeembrey'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
You can manually create a form data instance by calling popsicle.form
. When you pass a form data instance, it'll automatically set the correct Content-Type
- complete with boundary.
var form = popsicle.form({
username: 'blakeembrey',
profileImage: fs.createReadStream('image.png')
})
popsicle({
method: 'POST',
url: '/users',
body: form
})
All requests can be aborted before or during execution by calling Request#abort
.
var req = popsicle('http://example.com')
setTimeout(function () {
req.abort()
}, 100)
req.catch(function (err) {
console.log(err) //=> { message: 'Request aborted', aborted: true }
})
The request object can also be used to check progress at any time.
All percentage properties (req.uploaded
, req.downloaded
, req.completed
) will be a number between 0
and 1
. When the total size is unknown (no Content-Length
header), the percentage will automatically increment on each chunk of data returned (this will not be accurate). Aborting a request will automatically emit a completed progress event.
var req = popsicle('http://example.com')
req.uploaded //=> 0
req.downloaded //=> 0
req.progress(function (e) {
console.log(e) //=> { uploaded: 1, downloaded: 0, completed: 0.5, aborted: false }
})
req.then(function (res) {
console.log(req.downloaded) //=> 1
})
You can create a reusable cookie jar instance for requests by calling popsicle.jar
.
var jar = request.jar()
popsicle({
method: 'POST',
url: '/users',
jar: jar
})
Promises and node-style callbacks are supported.
Promises are the most expressive interface. Just chain using Request#then
or Request#catch
and continue.
popsicle('/users')
.then(function (res) {
// Things worked!
})
.catch(function (err) {
// Something broke.
})
For tooling that expect node-style callbacks, you can use Request#exec
. This accepts a single function to call when the response is complete.
popsicle('/users')
.exec(function (err, res) {
if (err) {
// Something broke.
}
// Success!
})
Every Popsicle response will give a Response
object on success. The object provides an intuitive interface for requesting common properties.
200 -> 2
)application/json
)All response handling methods can return an error. The errors can be categorized by checking properties on the error instance.
err.parse
)err.abort
)err.timeout
)err.unavailable
)err.blocked
)err.csp
)err.maxRedirects
)A simple plugin interface is exposed through Request#use
.
Plugins must be a function that accepts configuration and returns another function. For example, here's a basic URL prefix plugin.
function prefix (url) {
return function (req) {
req.url = url + req.url
}
}
popsicle('/user')
.use(prefix('http://example.com'))
.then(function (res) {
console.log(res.request.url) //=> "http://example.com/user"
})
If you need to augment the request or response lifecycle, there are a number of functions you can register. All listeners accept an optional promise that will resolve before proceeding.
resolve
or reject
Install dependencies and run the test runners (node and browsers using Karma).
npm install && npm test
MIT
FAQs
Advanced HTTP requests in node.js and browsers
The npm package popsicle receives a total of 78,631 weekly downloads. As such, popsicle popularity was classified as popular.
We found that popsicle demonstrated a healthy version release cadence and project activity because the last version was released less than 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
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.