首页 > 解决方案 > 如何在反应本机应用程序中获取带有标头的api(POST)

问题描述

我试图将三个参数放在我对特定 api 的发布请求中,但我没有得到预期的响应。API 在我的 Postman 中运行良好,但我不确定我在 react native 应用程序中的获取方法我是新手,所以我不知道如何在我的 api 请求中放置标头我遵循了一些文档但没有得到太多请看看并回答我的问题。

 constructor (props) {
        super (props)
        this.state = {
            detail: ''
        }
    }

    ComponentDidMount(){
        var data = new FormData();
        data.append('mobile_number','8615351655')
        data.append('mobile_country_code','+21')
        data.append('rec_name','Shantanu Talwaar')
    }
    fetchData = async() => {
        fetch('http://link.com/link/',
        {
            method: 'POST', 
            headers:{
                 //this what's exactly look in my postman
                'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;
            },
            body: this.data
        })
        .then((response) => response.json())
        .then((responseJson) => {
                alert(responseJson.detail)
        }).catch((error) => {
            alert('error')})}

  render() {
    return (
      <View style = {styles.container}>
        <Button onPress = {this.fetchData} title = "fetch"/>
        <Text style={styles.text}>Fetched data displays below</Text>
        <Text style={styles.text}>{this.state.detail}</Text>
      </View>
    )
  }
}

这是我现在在我的警报框中得到的结果:“未提供身份验证凭据。”

标签: jsonapireact-nativehttp-headersfetch-api

解决方案


您的令牌后缺少 '。

'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;

由于它是一个 JSON 对象,您应该删除分号

所以,最终的代码将是

'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'

还有另一个问题。无法从 fetch 函数访问数据声明。所以你应该做这样的事情。

fetchData = async() => {
    var data = new FormData();
    data.append('mobile_number','8615351655')
    data.append('mobile_country_code','+21')
    data.append('rec_name','Shantanu Talwaar')

    fetch('http://link.com/link/',
    {
        method: 'POST', 
        headers:{
            //this what's exactly look in my postman
            'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
        },
        body: data
    })
    .then((response) => response.json())
    .then((responseJson) => {
        alert(responseJson.detail)
    }).catch((error) => {
        alert('error')
    })
}

推荐阅读