This tutorial shows you how to use cURL to add users and perform GET/POST requests with a Node.js and Express.js sever.

Introduction

cURL is a transfer tool used to transfer data from or to a server. It supports various internet protocols of transfer, including:

  • DICT
  • FILE
  • FTP, FTPS
  • GOPHER
  • HTTP, HTTPS
  • IMAP, IMAPS
  • LDAP, LDAPS
  • POP3, POP3S
  • RTMP, RTSP
  • SCP, SFTP
  • SMB, SMBS
  • SMTP, SMTPS
  • TELNET and TFTP

We can perform useful tricks with cURL like proxy support, user authentication, FTP upload, HTTP post, SSL connections, cookies, file transfer resume, Metalink, and more.

Important: cURL is powered by libcurl for all transfer-related features.

cURL is used from the command-line. It’s mostly commonly used to quickly test out APIs during software development. I personally use cURL when I want to test out all my APIs in my Node.js server. It is a really handy tool for developers.

Postman is cool, but cURL is super-cool. – Chidume Nnamdi

In this post, we will go through basic cURL functions and options. We will also learn how we can use cURL to perform GET, POST requests on an API endpoint.

cURL options

--request or -X

--request and -X specify a custom request method you can use when communicating with the HTTP server. The specified request method will be used instead of the method otherwise used (which defaults to GET).

To perform a POST request:

curl --request POST

To perform a GET request:

curl --request GET

If we don’t specify the request via --request, it will default to GET.

--url</code

This specifies the URL that we will be fetching or transferring data to.

From the cURL docs:

Specify a URL to fetch. This option is mostly handy when you want to specify URL(s) in a config file.

If the given URL is missing a scheme name (such as “http://&#8221; or “ftp://&#8221;, etc) then cURL will make a guess based on the host.

If the outermost subdomain name matches DICT, FTP, IMAP, LDAP, POP3, or SMTP, then that protocol will be used. Otherwise, HTTP will be used.

For example, if you want to perform a GET request on your local server at localhost:3000, you’ll want to set the --url to be localhost:3000:

curl --request GET \
    --url http://localhost:3000

To perform a POST at the same URL:

curl --request POST \
    --url http://localhost:3000

Note: The backslash \ is used to separate options in cURL.

For an external API, it’s still the same thing.

Let’s say you want to fetch a list of movies from https://moviesdb.com/movies/all.

curl --request GET \
    --url https://moviesdb.com/movies/all

The list of all movies in moviesdb will be fetched and printed.

#node #javascript #web-development #api #programming

How to use cURL to Perform GET/POST Requests to a Node.js Server
93.85 GEEK