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