54

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.

wordSmith
  • 2,993
  • 8
  • 29
  • 50
  • 3
    in js you would use XMLHttpRequest instead of curl – Joe T Aug 26 '14 at 22:09
  • @JoeT So I could use jQuery's `$.get` then, I believe. But how do I pass the header and as an array? – wordSmith Aug 26 '14 at 22:10
  • You can take a look here: http://stackoverflow.com/questions/11312908/using-ajax-to-make-a-curl-request – ROMANIA_engineer Aug 26 '14 at 22:11
  • 1
    with XMLHttpRequest you can pass headers with setRequestHeader, but i don't know about w jQ's $.get – Joe T Aug 26 '14 at 22:12
  • 1
    @JoeT I'm getting a XMLHttpRequest cannot load https://api.wit.ai/message?v=20140826&q=. No 'Access-Control-Allow-Origin' header is present on the requested resource. How can I pass that header? – wordSmith Aug 26 '14 at 23:32
  • Anybody get here trying to do a curl request in node.js at the server and not in the browser?? Here's [a reference.](http://stackoverflow.com/questions/26695359/convert-curl-request-over-to-node-js-server-attach-data-to-the-request) – zipzit Jun 03 '16 at 19:52

4 Answers4

52

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
        }
})
Amir T
  • 2,708
  • 18
  • 21
  • 4
    I'm getting a `XMLHttpRequest cannot load https://api.wit.ai/message?v=20140826&q=. No 'Access-Control-Allow-Origin' header is present on the requested resource.` How can I pass that header? – wordSmith Aug 26 '14 at 22:43
  • Sounds like a cross domain issue. Thats a browser security thing. Google that error and/or ping me on a new question if that doesnt resolve it. – Amir T Aug 27 '14 at 02:59
  • Can someone explain how setRequestHeader is set ? I need to post a curl request to golang – Justinjs Feb 10 '16 at 11:43
  • The API will attach the allowed origins to the response headers of the call. Your domain or * needs to be there. The API you are trying to call can either probably be configured to allow your domain or they deliberately made it that way to enforce server to server usage as there is no CORS on the server side ( it's a browser implementation). Look into jsonp to potentially bypass this issue. – Dean Martin May 13 '17 at 10:02
21

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) );
JSON C11
  • 11,272
  • 7
  • 78
  • 65
  • fetch api does not work with "http" requests. I am facing error fetching a locally hosted api. – Akash Tyagi Apr 13 '20 at 10:06
  • 3
    @AkashTyagi If not HTTP what do you think is fetch using then? – undefined Jul 10 '21 at 16:04
  • 1
    If using node, import with following: `const fetch = require('node-fetch')`. Note that I needed to install `node-fetch` locally to make things works and don't realised why `node-fetch` globally installed did not worked. – danilocgsilva Aug 01 '21 at 15:25
3

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'));
?>
Pedro Serpa
  • 161
  • 5
  • 1
    If you have control over the server (and you'd also need this for the callback wrapper), using JSONP is hardly 'the only way to make cross domain calls'. Simply add CORS headers on the servers response(s) and it will also work fine without using JSONP. Plus, using normal GET's or POST's allow you to set headers, which is not possible with getJSON. – MikeOne Nov 02 '17 at 21:17
  • Well, yes, but I've found it not so effective recently. Kind of buggy on Firefox and this doesn't work well for mobile browsers. But I'll dig into it!! – Pedro Serpa Nov 02 '17 at 21:35
-2

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);
Aditya Mittal
  • 1,681
  • 16
  • 12
  • 1
    I'd highly recommend using [a provided http client from node](https://nodejs.org/api/http.html) rather than `exec` any given bash function/script. For example, passing `http://localhost'; || some_malicous_command #` as the url will allow for command injection. At the very least, you should check the provided parameter is a valid URL pattern. – OneCricketeer May 03 '22 at 17:07