【问题标题】:Can't fetch express API from React frontend无法从 React 前端获取 express API
【发布时间】:2020-03-23 13:59:32
【问题描述】:

我现在已经进入第三周尝试简单地从 Express API 获取 json 响应到 React 应用程序中。我已经尝试了至少 40 个小时的教程,但我仍然无法让它发挥作用。出于绝望,我想把它贴在这里,因为我知道我会被处以私刑,因为这将是某种重复,但我正在寻找能解决这个问题的人,希望能帮助我理解我做错了什么。

无论如何,这是我要调用的 API:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(express.static('jestproject'))
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

var todos = [{key:1, title:'eat'}, {key:2, title:'pray'}, {key:3, title:'love'}];

app.listen(3001, function (err) {
  if (err) {
  console.error('Cannot listen at port 3001', err);}
  console.log('Todo app listening at port 3001');
});

/////////////////////////////////////////////////////////////////////////////////
app.get('/', (req, res) => res.status(200).json(todos));

app.post('/post', (req, res) => {
    if(!req.body.title) {
        return res.status(400).send({
            success: 'false',
            message: 'title is required'
        });
    }

    const todo = {
        key: todos.length + 1,
        title: req.body.title
    }

    todos.push(todo);
    return res.send({todo})
});

app.put('/:key', (req, res) => {

    var key = parseInt(req.params.key, 10);

    if (todos[key - 1]){
        todos[key -1] = { 'key': key, title : req.body.title };
        res.status(200).send({
            success: 'true',
            message: 'Todo updated successfully'
        });
    } 
    else{
        res.status(404, 'The task is not found')
        .send()
    }
});

app.get('/:key', (req, res) => {

    const key = parseInt(req.params.key, 10);

    todos.map((todo) => {
        if (todo.key === key) {
            return res.status(200).send({todo});
        }
    });

    return res.status(404).send({
        success: 'false',
        message: 'todo does not exist'
    });
});

app.delete('/:key', (req, res) => {

    const key = parseInt(req.params.key, 10);

    todos.map((todo, index) => {
        if (todo.key === key) {
            todos.splice(index, 1);
            return res.status(200).send({
                success: 'true',
                message: 'Todo deleted successfuly',
            });
        }
    });

    return res.status(404).send({
        success: 'false',
        message: 'todo not found',
    });
});

app.put('/:key', (req,res) => {
    const key = parseInt(req.params.key);

    if(todos.key === key) {
        todo = req.body;

        return res.status(200).send({
            success: 'true',
            message: 'Todo Updated successfully',
        });
    }
});

module.exports = app;

这是我最近从 React 调用它的尝试

import React, { Component } from 'react';

class App extends Component {
   constructor(){
       super();
       this.state ={key: 0, title: ''};
   }
   componentDidMount() {
          fetch('http://localhost:3001/')
            .then(res => {
                console.log(res);
                return res.json()
             })
            .then(todos => { 
                console.log(todos); 
                this.setState({ todos })
             });
         }
   render() {
        return (
            <div className="App">
                <h1>todos</h1>
                {this.state.todos.map(todo =>
                <div key = {this.state.key} > title: {this.state.title} </div>
              )}
            </div>
        );
    }
}
export default App;

这会产生一个错误:Uncaught TypeError: Cannot read property 'map' of undefined

有人能解释一下获取这种格式的数据的正确方法吗?

【问题讨论】:

  • 你还没有用数组初始化this.state.todos
  • fetch('http://localhost:3001/') 出现什么错误?
  • @palaѕн 我得到 net::ERR_CONNECTION_REFUSED

标签: javascript reactjs api express


【解决方案1】:

你需要在构造函数中初始化todos

constructor(){
       super();
       this.state ={key: 0, title: '', todos: []};
   }

因为最初调用 render 方法时,API 仍在进行中,此时 todos 未定义。

因此,当您尝试在 undefined 上运行 .map 时,它会崩溃。

【讨论】:

  • 我修复了这个问题,但我现在在 fetch('localhost:3001/') 处得到一个 net::ERR_CONNECTION_REFUSED
【解决方案2】:

您的todos 将在componentDidMount 运行之前的初始render 期间未定义,因此您必须像这样使用空数组初始化todos

constructor(){
       super();
       this.state ={key: 0, title: '', todos: []};
   }

【讨论】:

  • 谢谢!我解决了这个问题,但我现在在 fetch('localhost:3001/') 处得到一个 net::ERR_CONNECTION_REFUSED
【解决方案3】:

我认为你混合了 state 和 todos 数组。 在构造函数中初始化状态如下:

constructor(){
   super();
   this.state ={ todos: [key: 0, title: '']};
}

在渲染函数中:

render() {
        return (
            <div className="App">
                <h1>todos</h1>
                {this.state.todos.map(todo =>
                <div key = {todo.key} > title: {todo.title} </div>
              )}
            </div>
        );
    }

【讨论】:

  • 这会产生一个错误:在使用 get 函数时,类型转换表达式应该用括号括起来 this.state ={ todos: [key: 0, title: '']};也许应该是 this.state ={ todos: {[key: 0, title: '']}};?抱歉,我对 js 和 React 非常陌生
猜你喜欢
  • 2023-02-07
  • 2021-07-01
  • 1970-01-01
  • 2019-04-11
  • 2022-01-25
  • 2022-01-21
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
相关资源
最近更新 更多