Reputation: 3183
Is it possible to send a curl request in jQuery or javascript?
Something like this:
curl \
-H 'Authorization: Bearer 6Q************' \
'https://api.wit.ai/message?v=20140826&q='
So, in PHP on submission of a form, like this:
$header = array('Authorization: Bearer 6Q************');
$ch = curl_init("https://api.wit.ai/message?q=".urlEncode($_GET['input']));
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close($ch);
What I'm trying to do is perform this curl request, which returns json and then I plan on parsing it with jQuery's $.get()
function.
Upvotes: 57
Views: 374678
Reputation: 1631
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,
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!
Upvotes: 0
Reputation: 1771
The currently accepted answer is for making ajax calls and you may have to deal with cross-site issues.
But if you're just wanting to run Linux curl on the server-side, as you do with PHP, then you can use this.
Here is my function to perform curl requests with nodejs.
It's a simple async function and no special packages outside of node are required. You can do what you want with the resulting data and error or return it to use in another async function.
I just logged for example.
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const goCurl = async (url) => {
const { stdout, stderr } = await exec(`curl '${url}'`);
console.log('data:', stdout);
console.error('err:', stderr);
}
const url = `https://static.canva.com/web/a7a51d4eae8626ead168.ltr.css`;
goCurl(url);
Upvotes: -2
Reputation: 2758
curl is a command in linux (and a library in php). Curl typically makes an HTTP request.
What you really want to do is make an HTTP (or XHR) request from javascript.
Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax
Essentially you will want to call $.ajax
with a few options for the header, etc.
$.ajax({
url: 'https://api.wit.ai/message?v=20140826&q=',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
}, success: function(data){
alert(data);
//process the JSON data etc
}
})
Upvotes: 55
Reputation: 11802
You can use JavaScripts Fetch API (available in your browser) to make network requests.
If using node, you will need to install the node-fetch package.
const url = "https://api.wit.ai/message?v=20140826&q=";
const options = {
headers: {
Authorization: "Bearer 6Q************"
}
};
fetch(url, options)
.then( res => res.json() )
.then( data => console.log(data) );
Upvotes: 22
Reputation: 161
Yes, use getJSONP. It's the only way to make cross domain/server async calls. (*Or it will be in the near future). Something like
$.getJSON('your-api-url/validate.php?'+$(this).serialize+'callback=?', function(data){
if(data)console.log(data);
});
The callback parameter will be filled in automatically by the browser, so don't worry.
On the server side ('validate.php') you would have something like this
<?php
if(isset($_GET))
{
//if condition is met
echo $_GET['callback'] . '(' . "{'message' : 'success', 'userID':'69', 'serial' : 'XYZ99UAUGDVD&orwhatever'}". ')';
}
else echo json_encode(array('error'=>'failed'));
?>
Upvotes: 3