【发布时间】: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