如何在本机应用程序中使用 header 获取 api(POST)

how to fetch api(POST) with header in react native app

我试图在我的 post 请求中添加三个参数给特定的 api 但我没有得到预期的响应。 API 在我的 Postman 中工作正常,但我不确定我的 React Native 应用程序中的获取方法我是新手所以我不知道如何将 headers 放入我的 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>
    )
  }
}

这是我现在在提醒框中的结果:"Authentication credentials were not provided."

您的令牌后缺少一个 '。

'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;

因为它是一个 JSON 对象,你应该删除分号

因此,最终代码将是

'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'

还有一个问题。无法从获取函数访问数据声明。所以你应该这样做。

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')
    })
}

我认为您可以使用 "x-access-token" 作为身份验证令牌的 header 名称并放置 Content-Type

fetchData = () => {
        fetch('http://link.com/link/',
        {
            method: 'POST', 
            headers:{
                'Content-Type': "application/json",
                'x-access-token': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
            },
            body: this.data
        })
        .then((response) => response.json())
        .then((responseJson) => {
                console.log(responseJson.detail)
        }).catch((error) => {
            alert('error')})
            }