簡體   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