简体   繁体   中英

Convert PHP Post API script into jQuery API call

I have access to some PHP code which I want to use on a NodeJs app with javascript on the server side instead of PHP - is there an easy way to convert the request from one format to another?

Here's the sample code:

<?php

$key="KEY";
$ch = curl_init("https://api.....".$key);
$opts = array(
    CURLOPT_POST => 1,
    CURLOPT_HTTPHEADER => array("Content-Type:multipart/form-data"),
    CURLOPT_POSTFIELDS => array(
        "user_audio_file" => "@"."/home/username/test.wav",
        "user_id" => 1234,
    ),
    CURLOPT_RETURNTRANSFER => true
);

curl_setopt_array($ch,$opts);
$raw = curl_exec($ch);
if(curl_errno($ch) > 0) {
    echo("There was an error using the api: ".curl_error($ch));
}
else {
    var_dump($raw);
}

curl_close($ch);
?>

You could use the Fetch API

const key = "KEY";

let fd = new FormData();
fd.append("user_audio_file", "@"+"/home/username/test.wav");
fd.append("user_id", 1234);

fetch(`https://api.....${key}`, { method:'post', body:fd, credentials:'same-origin' })
.then((r) => {
    return r.json();
})
.then((r) => {
    // use json response here...
});

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