尝试使用下面的代码在React中发出POST请求。为了保护隐私,我删除了实际参数,并为url,accesskey和varArgs变量插入了假参数。当我尝试启动我收到的请求时 - '错误:无法加载空网址'。我的url变量是一个有效的字符串,post请求可以正常工作。谁能看到我做错了什么?
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
Picker
} from 'react-native';
var vsprintf = require('sprintf-js').vsprintf
class plantMetrics extends Component {
constructor(props){
super(props)
const url = 'http://myurl.com'
const accessKey = 'myaccesskey'
const varArgs = '{"arg1":"val1"}'
this.state = {
catalogMeta: 'shit',
workspace: '',
measure: '',
bu: '',
country: '',
plant: '',
region: ''
}
}
getCatalogInfo(){
fetch(this.url, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Authorization': this.accessKey
},
body: this.varArgs
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({catalogMeta: JSON.stringify(responseJson.body)})
})
.catch((error) => {
this.setState({catalogMeta: 'error: ' + error})
})
}
render() {
return (
<View>
<Text>{"\n"}</Text>
<Text>{this.state.catalogMeta}</Text>
<TouchableHighlight onPress={this.getCatalogInfo.bind(this)}>
<Text>Fetch</Text>
</TouchableHighlight>
</View>
);
}
答案 0 :(得分:0)
以下变量
const url = 'http://myurl.com'
const accessKey = 'myaccesskey'
const varArgs = '{"arg1":"val1"}'
仅在constructor
方法的范围内。要通过this
访问它们,请使用this
:
this.url = 'http://myurl.com'
this.accessKey = 'myaccesskey'
this.varArgs = '{"arg1":"val1"}'