使用Express实现本机JSON API网络

问题描述 投票:0回答:1

我正在尝试使用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个回答
0
投票

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

我建议使用这个完整的URL来获取获取请求,而不仅仅是/ users路径。防爆/

fetch('http://localhost:4567/users')
.then(response => response.json())
.then(data => {
this.setState({
users: true
})
© www.soinside.com 2019 - 2024. All rights reserved.