【问题标题】:React Native JSON API Networking With Express使用 Express 反应原生 JSON API 网络
【发布时间】:2018-08-31 16:05:21
【问题描述】:

我正在尝试使用 Express 服务器/PostgreSQL 数据库创建 React Native 应用程序。我的一个组件中有以下获取请求

componentDidMount() {
    fetch('/users')
    .then(response => response.json())
    .then(data => {
    this.setState({
        users: true
      })
    })
   }

“/users”端点在我的服务器文件中定义为:

app.get('/users', (request, response) => {
   Users.all().then(users => {
   const templateData = {};
   templateData.data = users;
   response.json(templateData);
  })
});

服务器正在监听 4567 端口

在 package.json 中,我有一个这样的代理设置:

"proxy": "http://localhost:5000/",

我的问题是,当调用 componentDidMount 时,我不断收到“网络请求失败”错误。关于如何让我的服务器与我的组件通信的任何想法?谢谢!

【问题讨论】:

    标签: json ajax express react-native network-programming


    【解决方案1】:

    我以前没有使用过“代理”,但您的第一个问题是您的 URL 路径包含错误的端口。如果您的服务器正在侦听端口 4567,则您的 URL 路径应为“http://localhost:4567”。

    我建议您使用这个完整的 URL 发出您的 fetch 请求,而不仅仅是 /users 路径。 例如/

    fetch('http://localhost:4567/users')
    .then(response => response.json())
    .then(data => {
    this.setState({
    users: true
    })
    

    【讨论】:

    • 嗨,尼尔,非常感谢您的回复。我删除了代理并修改了包含本地主机和端口的路径,但不幸的是我得到了同样的错误:[
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多