In my React code I send a 'post' and 'get' request. My problems are in my server side code, I think.
General
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"
}
];
Note: Context, code above comes before the problem code
Resolved 1) Post
User clicks 'Submit' a post request sends data to server
Problem:
1) The 'req.body' is empty
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);
})
Solution:
POST request is sending data in JSON format because of JSON.stringify(post)
, we need to parse this JSON data so we can use app.use(bodyParser.json());
, and there we have it. SOLVED
Resolved 2) Get
In the first get request I am sending the 'id' of the object as URL params and trying to receive the corresponding object from the server, req is sent correctly.
Problem: Receive the following error in the 'findPostById' function:
TypeError: Cannot read property id of undefined
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));
}
}
Solution:
post.id
is type 'number' and id is of type 'string', return post.id === id;
result in false because of strict equality. So, we convert id to number with +id
`return post.id === +id;
Check if in your server side code is missing below configuration.
const bodyParser = require("body-parser");
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: false }));
body parser allows you to access req.body from within your routes
For problem 1,
Please try to add this.
app.use(bodyParser.json());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.