0

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;

9
  • Try renaming the key from 'body' to 'postdata' in the fetch request. Commented Oct 30, 2019 at 12:15
  • 1
    For 1) The error means that post.id === id is never true and thus posts.find returns undefined. There is not much we can do to help you here since we don't know what posts contains or what the value of id is. Commented Oct 30, 2019 at 12:18
  • As for 2), from the documentation: "req.body Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded()." So it looks like you didn't setup the middleware correctly. Commented Oct 30, 2019 at 12:19
  • @FelixKling Yes, I did parse the 'req.body' using body-parser library Commented Oct 30, 2019 at 12:27
  • @FelixKling Yes, the error is with posts.find... but what is the problem? Commented Oct 30, 2019 at 12:35

2 Answers 2

1

For problem 1,

Please try to add this.

app.use(bodyParser.json());

Sign up to request clarification or add additional context in comments.

3 Comments

I tried it does not work. The problem is I don't even receive data from the POST request, need to resolve this before we can worry about storing the data
Please try to add method-override. const methodOverride = require('method-override'), // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride());
Did not need to convert posts to JSON, just needed to add app.use(bodyParser.json());
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.