Convert curl to Node.js Axios

Convert curl commands to Node.js Axios HTTP client code. Handle interceptors, automatic JSON transforms, error handling, and request configuration.

Node.js

Detailed Explanation

Converting curl to Node.js Axios

Axios is one of the most popular HTTP clients for Node.js and browsers, offering automatic JSON transformation, interceptors, and a clean API. It is the go-to library for many Node.js developers.

GET Request

curl:

curl https://api.example.com/users

Axios:

const axios = require("axios");

const { data } = await axios.get("https://api.example.com/users");

Axios automatically parses JSON responses, so you do not need to call .json() like with fetch.

POST with JSON

curl:

curl -X POST https://api.example.com/users \
  -H "Content-Type: application/json" \
  -d '{"name": "Alice"}'

Axios:

const { data } = await axios.post("https://api.example.com/users", {
  name: "Alice",
});

Axios automatically serializes objects to JSON and sets the Content-Type header.

Custom Headers and Auth

curl:

curl -H "Authorization: Bearer token123" \
  -H "X-Custom: value" \
  https://api.example.com/me

Axios:

const { data } = await axios.get("https://api.example.com/me", {
  headers: {
    "Authorization": "Bearer token123",
    "X-Custom": "value",
  },
});

File Upload

curl:

curl -F "file=@photo.jpg" https://api.example.com/upload

Axios:

const FormData = require("form-data");
const fs = require("fs");

const form = new FormData();
form.append("file", fs.createReadStream("photo.jpg"));

const { data } = await axios.post("https://api.example.com/upload", form, {
  headers: form.getHeaders(),
});

Error Handling

Axios throws errors for non-2xx status codes, unlike fetch:

try {
  const { data } = await axios.get("https://api.example.com/data");
} catch (error) {
  if (error.response) {
    console.log(error.response.status, error.response.data);
  }
}

Axios vs Fetch

Axios provides automatic JSON parsing, request/response interceptors, built-in timeout support, and better error handling out of the box, making it particularly well suited for complex Node.js applications.

Use Case

A Node.js backend developer needs to convert curl commands into Axios calls for a microservice that communicates with external APIs and requires interceptors for logging.

Try It — Curl to Code Converter

Open full tool