Since you can use Javascript in two different place: Client and Server, I'll try to share for both.
First for client usage:
Javascript has native Ajax support, with XMLHTTPRequest (but it's harder to work with)
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/api/data", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send();
I would use Fetch API instead, as it's more friendly:
fetch('http://example.com/api/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Fetch error:', error));
Now for the server:
you have several options for running cURL in javascript/NodeJs,
- Using exec command, to execute a command, including cURL
- Using node-libcurl, as a binding to the libcurl API
- Use the alternative with the same goal! As the goal for cURL is request to HTTP, we have several options here, including:
- request
- build in HTTPS
- got
- needle
- etc..
I wrote more about this here: How to use cuRL in Javascript and it's alternative., feel free to read.
Example for exec comamnd
const { exec } = require('child_process');
exec('curl -s https://example.com', (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error}`);
return;
}
if (stderr) {
console.error(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
Example for node-libcurl
const { curly } = require('node-libcurl');
async function run() {
const { statusCode, data, headers } = await curly.get('https://www.google.com')
console.log(statusCode)
console.log('---')
console.log(data)
}
run();
Example for Axios (as an alternative)
const axios = require('axios');
const fs = require('fs');
Axios.get('https://example.com')
.then(response => {
fs.writeFile('index.html', response.data, (err) => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('File saved as index.html');
}
});
})
.catch(error => {
console.error('Error fetching URL
:', error);
});
I hope it helps!
$.getthen, I believe. But how do I pass the header and as an array?