![](/img/trans.png)
[英]React Native + fetch + API : DELETE request fails in App, works in Postman
[英]how to fetch api(POST) with header in react native app
我試圖在我的帖子請求中將三個參數放到特定的api但我沒有得到我預期的響應。 API在我的郵遞員中工作正常,但我不確定我的反應本機應用程序中的提取方法我是新手,所以我不知道如何在我的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>
)
}
}
這是我現在在警報框中的結果:“未提供身份驗證憑據。”
你的令牌后有一個'丟失'。
'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”作為身份驗證令牌的標題名稱,也可以使用“ 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')}) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.