NodeJS SuperAgent: How to Send POST Requests
SuperAgent allows you to configure an http request parameters such as url, body and headers by chaining various methods.
To send POST requests with SuperAgent, first create a new post request by calling request.post
method with url
as an argument. Then set the post body
by using send
method of the request. To configure a request header, just chain set
method with previous call to send
method and provide the header name (Content-Type) and value (application/json):
const request = require("superagent");
const url = 'https://httpbin.org/post';
const body = { key: 'value' };
request.post(url)
.send(body)
.set('Content-Type', 'application/json')
.then(response => {
console.log(response.body);
})
.catch(error => {
console.error(error);
});
In this guide for The NodeJs Web Scraping Playbook, we will look at how to make POST
requests with the NodeJS SuperAgent.
In this guide we will walk you through the most common ways of sending POST requests with NodeJS SuperAgent:
Let's begin...
Need help scraping the web?
Then check out ScrapeOps, the complete toolkit for web scraping.
POST JSON Data Using NodeJS SuperAgent
A common scenario for using POST
requests is to send JSON data to an API endpoint, etc. Making POST requests this with NodeJS SuperAgent is very simple.
You simply just need to call request.post
method with url
and follow that with a call to send
method prividing the request body
as an argument:
const request = require("superagent");
const url = 'https://httpbin.org/post';
const body = { key: 'value' };
request.post(url)
.send(body)
.set('Content-Type', 'application/json')
.then(response => {
console.log(response.body);
})
.catch(error => {
console.error(error);
});
POST Form Data Using NodeJS SuperAgent
Another common use case for using POST
requests is to send form data to an endpoint.
To make form data POST requests with SuperAgent we simply need to set the data to the request by calling the send
method:
const querystring = require('querystring');
const request = require("superagent");
const url = 'https://httpbin.org/post';
const data = { key: 'value' }
const body = querystring.stringify(data);
request.post(url)
.send(body)
.set('Content-Type', 'application/x-www-form-urlencoded')
.then(response => {
console.log(response.body)
})
.catch(error => {
console.error(error);
});
Here we set the Content-Type
header to application/x-www-form-urlencoded
so that the body
will be picked up as form data. Also note that we have set body
to a string representation of data
calculated using querystring.stringify
function.
More Web Scraping Tutorials
So that's how you can send POST requests using NodeJs SuperAgent.
If you would like to learn more about Web Scraping, then be sure to check out The Web Scraping Playbook.
Or check out one of our more in-depth guides: