【问题标题】:The localhost api can not be fetched from the expo无法从博览会获取 localhost api
【发布时间】:2019-05-31 14:45:25
【问题描述】:

无法从 expo 中获取 localhost api。

常量搜索 = async(type) => { 让响应 = 等待 fetch(http://localhost:3000/api/${type}, { 接受:'应用程序/json' }); 让结果 = 等待 response.json(); 返回结果; }

const create = async(type, data) => { 让响应=等待获取(http://localhost:3000/api/${type},{ 标题:{ '接受': '应用程序/json', “内容类型”:“应用程序/json” }, 方法:'发布', 正文:JSON.stringify(数据) }); 让结果 = 等待 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;

【问题讨论】:

  • 使用你电脑的真实IP地址
  • 请格式化您的帖子(您使用过代码的地方)。

标签: reactjs react-native expo


【解决方案1】:

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

试试下面的:

  1. https://ngrok.com/注册后按照步骤安装
  2. 解压后打开终端和./ngrok http &lt;port_number&gt;
  3. 如果它工作正常,您应该看到Forwarding: &lt;forwarding_address&gt;
  4. 将此转发地址复制为您在应用中的基本网址
  5. 只是为了测试,尝试在浏览器中点击此转发地址,例如。 http://1a6b3022.ngrok.io/api/testing你应该得到回复

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2020-05-21
    • 2021-01-19
    • 2021-08-09
    相关资源
    最近更新 更多