繁体   English   中英

将PHP Post API脚本转换为jQuery API调用

[英]Convert PHP Post API script into jQuery API call

我可以访问一些我想在NodeJs应用程序上使用的PHP代码,而不是PHP在服务器端使用JavaScript-是否有一种简单的方法可以将请求从一种格式转换为另一种格式?

这是示例代码:

<?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);
?>

您可以使用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...
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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