axios 如何从API中获取来自PHP文件的数据

mkh04yzy  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(114)

我试图从API中获取数据,但问题是API有PHP扩展。我对这件事很陌生,我真的不明白为什么我不使用result.data来获取数据。

var formdata = new FormData();
formdata.append("stock_symbol", "PPL");

var requestOptions = {
    method: 'POST',
    body: formdata,
    redirect: 'follow'
};

fetch(url, requestOptions)
    .then(response => response.text())
    .then(
        result => {
            console.log('result', result.data)

        }

    )

    .catch(error => console.log('error', error));

字符串

ni65a41a

ni65a41a1#

从哪里获取数据并不重要,你犯了一个愚蠢的错误,数据格式是JSON,但你强行将其转换为原始文本,所以你必须用唯一的结果来替换result.data

var formdata = new FormData();
formdata.append("stock_symbol", "PPL");

var requestOptions = {
    method: 'POST',
    body: formdata,
    redirect: 'follow'
};

fetch("https://dev-api.sarmaaya.pk/3.0/company_fundamentals.php", requestOptions)
    .then(response => response.text())
    .then(
        result => {
            console.log('result', result) //now works
        }
    )
    .catch(error => console.log('error', error));

字符串
要使request.data工作,必须将response.text()替换为response.json()

var formdata = new FormData();
formdata.append("stock_symbol", "PPL");

var requestOptions = {
    method: 'POST',
    body: formdata,
    redirect: 'follow'
};

fetch("https://dev-api.sarmaaya.pk/3.0/company_fundamentals.php", requestOptions)
    .then(response => response.json())
    .then(
        result => {
            console.log('result', result.data) //now it works
        }
    )
    .catch(error => console.log('error', error));

相关问题