简体   繁体   中英

Convert CURL request into javascript

Can you please help me to convert this curl post request into a javascript(Axios) request?

    
https://url.com/api/send.php

function send_sms($url,$apikey,$smsno=1,$destination,$content){
    $fields = array(
       'apikey' => $apikey,
       'smsno' => $smsno,
       'destination' => $destination,
       'content' => $content
    );
    $fields_string = http_build_query($fields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $output;
}

Using fetch can help you convert a CURL command to fetch code.

Since fetch is open source, you can modify or extend the source code at will.


You can also copy a request recorded with the Chrome DevTools as a fetch.

https://github.com/kigiri

Source: kigiri

The following example will do the job:

function send_sms(apikey, smsno, destination, content){
    axios({
        method: 'post',
        url: 'https://url.com/api/send.php',
        data: {
            apikey: apikey,
            smsno: smsno,
            destination: destination,
            content: content
        }
    }).then((response) => {
        console.log(response);
    }, (error) => {
        console.log(error);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM