Perform curl request in javascript?

后端 未结 3 1015
谎友^
谎友^ 2020-12-02 09:56

Is it possible to send a curl request in jQuery or javascript?

Something like this:

curl \\
-H \'Authorization: Bearer 6Q************\' \\
\'https:/         


        
相关标签:
3条回答
  • 2020-12-02 10:24

    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) );
    
    0 讨论(0)
  • 2020-12-02 10:43

    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
            }
    })
    
    0 讨论(0)
  • 2020-12-02 10:43

    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'));
    ?>
    
    0 讨论(0)
提交回复
热议问题