Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform curl request in javascript?

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.

like image 539
wordSmith Avatar asked Aug 26 '14 22:08

wordSmith


People also ask

Can you do curl in JavaScript?

To make a GET request using Curl, run the curl command followed by the target URL. Curl automatically selects the HTTP GET request method unless you use the -X, --request, or -d command-line option.

What is a curl request?

'cURL' is a command-line tool that lets you transmit HTTP requests and receive responses from the command line or a shell script.


2 Answers

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         } }) 
like image 117
Amir T Avatar answered Oct 03 '22 12:10

Amir T


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) ); 
like image 22
JSON C11 Avatar answered Oct 03 '22 12:10

JSON C11