【问题标题】:How to fetch data in react native?如何在本机反应中获取数据?
【发布时间】:2019-06-04 12:21:05
【问题描述】:

我需要从以下格式的传递参数中获取数据,因为在 Postman 中进行测试时,只有这种格式会给出响应。

"json": {"model":"DB11 AMR","modelyear":"2019","locale":"AA"}

请您帮忙从以下服务器 url 获取数据。 https://vhapp.azurewebsites.net/myAMLModelSelection

下面是我的代码

var url = 'http://vhapp.azurewebsites.net/myAMLModelSelection'
        try {
            let response = fetch(url, {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    "json" : { "locale": "AA", "model" : "DB11 AMR", "modelyear" : "2019" }
                })

            })

            .then(res => res.text())          // convert to plain text
            .then(text => {
                console.log(text)
                alert(text)
                var res = text.substring(1, text.length-2);
                var obj = JSON.parse(res);
                alert(obj.cars[0].name)

            })
            .catch((error) => {
                console.error(error);
            });
        } catch (errors) {
            console.log(errors);
        }

这是我需要的回复

({"cars":[{"name":"DB11 AMR","content":{"guide":"http://cdntbs.astonmartin.com/360ss/OwnersGuides/KY53-19A321-AC. pdf","assets":[{"intAssetId":"115","intVehicleId":"1","strType":"pdf","strName":"附件手册","strDescription":null,"strLocation ":"http://cdntbs.astonmartin.com/360ss/iPad/myaml/brochures/Accessories Brochure English - 706435-PK.pdf","intVersion":"1","intOrder":"1"}]} }]});

【问题讨论】:

    标签: react-native


    【解决方案1】:

    您可以使用JS fetch API获取数据。

    export async fetchMyData(){
      try{
       let f = await fetch('https://vhapp.azurewebsites.net/myAMLModelSelection',{method:'GET'})
       let data = await f.json();
       return data;
      }catch(err){
        console.log(err)
      }
    }
    

    并在您的组件中调用此方法,例如:

    import {fetchMyData} from './file_name'
    
    fetchMyData().then((response)=>{console.log(response)})
    

    【讨论】:

    • 你能解释一下,如何传递参数来获取数据吗?
    • 你可以像这样使用 fetch POST 方法: export async fetchMyData(){ try{ let f = await fetch('vhapp.azurewebsites.net/myAMLModelSelection',{method:'POST',data:JSON.stringyfy( {name:'John Doe',email:'test@emailer.io'})}) let data = await f.json();返回数据; }catch(err){ console.log(err) } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多