【发布时间】:2019-11-17 11:33:37
【问题描述】:
在我的 React 代码中,我发送了一个“发布”和“获取”请求。我想我的问题出在我的服务器端代码上。
常规
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
const posts = [
{
"postId": 1,
"id": 1,
"title": "To be or not to be",
"body": "Yes, that is the question"
},
{
"postId": 1,
"id": 2,
"title": "So What?",
"body": "What do you want"
}
];
注意:上下文,上面的代码在问题代码之前
已解决 1) 发布
用户点击“提交”一个发布请求将数据发送到服务器
问题:
1) “req.body”为空
fetch("http://localhost:3001/create", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
.then(res => this.props.history.push('/posts'))
.catch(err => this.setState({error: true}))
this.setState({
title: "",
body: ""
})
app.post('/create', (req, res, next)=>{
// Request body is empty, why?
console.log(req.body);
})
解决方案:
由于JSON.stringify(post),POST 请求正在以 JSON 格式发送数据,我们需要解析此 JSON 数据,以便我们可以使用app.use(bodyParser.json());,然后我们就有了。解决了
已解决 2) 获取
在第一个获取请求中,我将对象的“id”作为 URL 参数发送并尝试从服务器接收相应的对象,req 被正确发送。
问题:在“findPostById”函数中收到以下错误:
TypeError: 无法读取未定义的属性 id
fetch(`http://localhost:3001/posts/${this.props.match.params.id}`)
.then(res=>res.json())
.then(data=>this.setState({loadedPost: data}))
.catch(err=>console.log(err))
app.get('/posts/:id', (req, res, next)=>{
// Correct, receive id
let id = req.params.id;
findPostById(id, (post, err)=>{
if(err){
console.log(err);
}
else{
res.send(post)
}
})
})
let findPostById = (id, cb)=>{
console.log(id, 'Correctly receive the id');
let post = posts.find((post)=>{
return post.id === id;
})
// Receive: 'TypeError: Cannot read property id of undefined'
console.log(post.id);
if(post){
cb(post, null);
}
else{
cb(null, new Error('Could not find post', id));
}
}
解决方案:
post.id 是 'number' 类型, id 是 'string' 类型,返回 post.id === id; 因为严格相等,所以返回 false。所以,我们用+id `return post.id === +id; 将id转换为数字;
【问题讨论】:
-
尝试在获取请求中将密钥从“body”重命名为“postdata”。
-
For 1) 错误意味着
post.id === id永远不是true,因此posts.find返回undefined。由于我们不知道posts包含什么或id的值是什么,因此我们无能为力。 -
至于2),来自documentation:"
req.body包含请求体中提交的数据键值对,默认为undefined,为当您使用诸如express.json()或express.urlencoded()之类的正文解析中间件时填充。" 所以看起来您没有正确设置中间件。 -
@FelixKling 是的,我确实使用 body-parser 库解析了“req.body”
-
@FelixKling 是的,
posts.find的错误是...但问题是什么?
标签: javascript reactjs express