json - 如何在反应本机应用程序中获取带有标头的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>
)
}
}
这是我现在在我的警报框中得到的结果:“未提供身份验证凭据。”
解决方案
您的令牌后缺少 '。
'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')
})
}
推荐阅读
- ios - 有没有办法从我的主类连接或访问我的“scrollView”到另一个类?
- java - OpenCV 4.1.0 Java:尝试将 BFMatcher 与基于 ORB 的关键点和描述符一起使用时如何修复“未知异常”?
- reactjs - TypeScript 和 React JS 访问 DOM 元素
- .net - 从 .net 客户端订阅 IBM MQ 主题
- c# - 如何获取有关找到该术语的字段的信息
- r - 将 na.rm 作为参数添加到 r 中的自定义函数
- javascript - 文本对齐 froalaEditor
- image - Github Markdown 中的图片缩略图
- java - 如何设置通知的标题和内容?
- python - 两个 CNN 模型输出的组合