React Native Post错误'无法加载空网址'

时间:2016-09-11 23:07:29

标签: post react-native

尝试使用下面的代码在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>
    );
  }

1 个答案:

答案 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"}'