2016-09-11 57 views
1

嘗試使用下面的代碼在React中發出POST請求。爲了保持隱私,我已經刪除了實際的參數,併爲url,accesskey和varArgs變量插入了僞造的參數。當我嘗試啓動請求時,我越來越 - '錯誤:無法加載空的網址'。我的網址變量是一個有效的字符串,發佈請求從curl工作正常。任何人都可以看到我做錯了什麼?反應本機發布錯誤'無法加載空的URL'

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

下面

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"}' 
+0

新手的錯誤,現在的工作表示感謝。 – kayzej1141