无法从博览会获取localhost API

时间:2019-01-05 04:14:23

标签: reactjs react-native expo

无法从博览会获取本地api。

const search = async(type)=> {     let response =等待fetch(http://localhost:3000/api/${type},{         接受:“ application / json”     });     让结果=等待response.json();     返回结果; }

const create = async(type,data)=> {     let response =等待fetch(http://localhost:3000/api/${type},{         标头:{             'Accept':'application / json',             '内容类型':'应用程序/ json'         },         方法:“发布”,         正文:JSON.stringify(data)     });     让结果=等待response.json();     返回结果; }

const Client = {搜索,创建}; 导出默认客户端;

Client.js

const search = async(type) => {
let response = await fetch(`http://localhost:3000/api/${type}`, {
    accept: 'application/json'
});
let result = await response.json();
return result; }

const create = async(type, data) => {
let response = await fetch(`http://localhost:3000/api/${type}`, {
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    method: 'post',
    body: JSON.stringify(data)
});
let result = await response.json();
return result;
}

const Client = {search, create};

export default Client;

App.js

import React, { Component } from 'react';
import {
  Text,
  View,
  TextInput,
  Button,
  StyleSheet

} from "react-native";
import Client from './Client.js';



class App extends Component {

  constructor() {
    super()
    this.state = {
      users: [] // user에 대한 정보를 담기 위한 state
    }
    this.handleUserInputChange = this.handleUserInputChange.bind(this)
  }

  componentWillMount = () => {
    this.getUser()
  }

  handleUserInputChange = event => {
    const {target: {name, value}} = event
    this.setState({
      [name]: value
    });
  }

  getUser = async() => {
    Client.search('User') // Client.js에서 
    .then(data => {
      this.setState({
        users: data 
      })
    })
  }

  submitUser = () => {
    const data = {
      "$class": "org.acme.model.User",
      "phonenumber": this.state.phonenumber,
      "email": this.state.email,
      "firstName": this.state.firstName,
      "lastName": this.state.lastName,

    }

    Client.create('User', data)
    .then(() => {
      this.getUser()
    })
  }

  render() {
    return(
      <View className="App">
        <Text>Add User</Text>
        <Text>phonenumber:</Text>
        <TextInput 
          onChange={this.handleUserInputChange}
          type="text"
          name="phonenumber" />
        <Text>email:</Text>
        <TextInput
          onChange={this.handleUserInputChange}
          type="text"
          name="email" />
        <Text>firstName:</Text>
        <TextInput 
          onChange={this.handleUserInputChange}
          type="text"
          name="firstName" />
        <Text>lastName:</Text>
        <TextInput 
          onChange={this.handleUserInputChange}
          type="text"
          name="lastName" />

        <Button title="New User" onPress={()=> this.submitUser}/>



        <View style={styles.container}>
          <Text style={styles.userlist}>
            User List
          </Text>
          {this.state.users.map((r, i) => (
            <View style={styles.userstate}
                  key={i}>
          <Text>phonenumber: {r.phonenumber}</Text>
          <Text>email: {r.email}</Text>
          <Text>firstName: {r.firstName}</Text>
          <Text>lastName: {r.lastName}</Text>
        </View>
          ))}
      </View>
    </View>
    )
  }
}

const styles=StyleSheet.create({
  container: {
    flex:1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  userlist:{
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  userstate:{
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

export default App;

1 个答案:

答案 0 :(得分:0)

您必须公开您的API。一种方法是使用ngrok。

请尝试以下操作:

  1. https://ngrok.com/,并在注册后按照安装步骤进行操作
  2. 解压缩打开的终端和./ngrok http <port_number>
  3. 如果它正在运行,您应该会看到一个Forwarding: <forwarding_address>
  4. 将此转发地址复制为应用中的基本网址
  5. 要进行测试,请尝试在您的浏览器中找到该转发地址,例如。 http://1a6b3022.ngrok.io/api/testing您应该得到答复

希望这会有所帮助!