-1

I'm making a movie review app with React. I have an express server connecting to my localhost mySQL database. The connection and functions work but for some reason the req.body.value returns "undefined" in the app.get(/get) function but I get a working return in the app.post(/insert) function that is just right below that. The front-end function has the right value and it's showing in console.log just fine. What am I missing?

Express server:

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

const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "admin",
    database: "mymovies_jami"
});

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.json());

app.get('/get', (req, res) => {
    console.log(req.body.username); /* This returns undefined*/
    const username = req.body.username;
    const sqlGet = `SELECT * FROM movie_reviews_${username} ORDER BY id DESC LIMIT 10`
    connection.query(sqlGet, (err, result) => {
        res.send(result)
        console.log(err)
    });
});

app.post('/insert', (req, res) => {
    console.log(req.body.username); /* This works just fine*/
    const username = req.body.username;
    const movie_id = req.body.movie_id;
    const movieName = req.body.movieName;
    const movieComment = req.body.movieComment;
    const movieWatched = req.body.movieWatched;
    const poster_image = req.body.poster_image;
    const sqlInsert = `INSERT INTO movie_reviews_${username} (movieName, movieComment, movieWatched, poster_image, movie_id) VALUES (?,?,?,?,?)`;
    connection.query(sqlInsert, [movieName, movieComment, movieWatched, poster_image, movie_id], (err, result) => { console.log(err) });
});

Front-end GET:

import React from 'react';
import axios from 'axios';
import './style.css';
import { ModalDimmer } from 'semantic-ui-react';

class CrudGet extends React.Component {

    state = { username: "jami", recentlyW: [], variable: 5, buttonText: 'Show more...', show: false }

    componentDidMount() {
        this.getMovies(this.state.recentlyW);
    }

    componentDidUpdate(recentlyW) {
        if (this.state.recentlyW !== recentlyW) {
            console.log(this.state.recentlyW)
        }
    }

    getMovies = async () => {
        const res = await axios.get('http://localhost:3301/get', {
            username: this.state.username,
        })
        this.setState({ recentlyW: res.data })

    }

    render() {

        const showMore = () => {
            if (this.state.show === true) {
                this.setState({ variable: 5 })
                this.setState({ buttonText: "Show more..." })
                this.setState({ show: false })
            } else {
                this.setState({ variable: 10 })
                this.setState({ buttonText: "Show less..." })
                this.setState({ show: true })
            }
            console.log(this.state.show)

        }

        const tmdb = 'https://www.themoviedb.org/movie/'


        return (
            <>{this.state.recentlyW ? (
                <div >
                    {this.state.recentlyW.slice(0, `${this.state.variable}`).map(recent => (

                        <div className="item" key={recent.id}>
                            <details>
                                <img className='poster_recently' src={recent.poster_image} />
                                <summary> {recent.movieName}</summary>
                                <br></br>
                                <p></p>
                                <p>Comment: {recent.movieComment}</p>
                                <p>Watched: {recent.movieWatched?.substring(0, 10)}</p>
                                <p><a href={tmdb + recent.movie_id} target='_blank'>Movie in The Movie Database</a></p>
                            </details>
                        </div>
                    ))
                    }<br /><button className='ui button' onClick={showMore}>{this.state.buttonText}</button>
                </div>

            ) : (<div className='errormsg'><p className='error'>Could not connect to database. Check connection and username/password.</p></div>)
            }</>
        )
    }

}

export default CrudGet;

Front-end INSERT:

import React from 'react';
import axios from 'axios';
import './style.css';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
import './style.css';

class CrudPost extends React.Component {

    state = { movieName: '', movieComment: '', movieWatched: '', startDate: (new Date()), poster_image: '', username: '', movie_id: '' }



    render() {

        const nimivaihdos = () => {
            this.setState({ username: getUser })
            this.setState({ movieName: movie_name })
            this.setState({ poster_image: movie_poster })
            this.setState({ movie_id: movieID })

        }

        var getUser = window.localStorage.getItem('username')
        var getUser = getUser.substring(1, getUser.length - 1)
        var movie_poster = window.localStorage.getItem('movie_poster')
        var movie_poster = movie_poster.substring(1, movie_poster.length - 1)
        var movie_name = window.localStorage.getItem('movie_name')
        var movie_name = movie_name.substring(1, movie_name.length - 1)
        var movieID = window.localStorage.getItem('movie_id')

        const submitReview = () => {
            axios.post('http://localhost:3301/insert', {
                username: this.state.username,
                movie_id: this.state.movie_id,
                movieName: this.state.movieName,
                movieComment: this.state.movieComment,
                movieWatched: this.state.movieWatched,
                poster_image: this.state.poster_image
            }).then(() => {
                alert('Great success!')
            })
        }
        return (



            <div className='ui grid'>
                <div className='two column row'>
                    <div className='column'>
                        <img className='poster' src={movie_poster} />
                    </div>
                    <div className='column'>
                        <form className='ui form'>

                            <div className='field'>Movie Name
                                <input type='text' placeholder={movie_name} onClick={nimivaihdos} onChange={(event) => this.setState({ movieName: event.target.value })}
                                    value={this.state.movieName}></input>
                            </div>
                            <div className='field'>Comment
                                <textarea rows='2' placeholder='Write your movie comment' onChange={(event) => this.setState({ movieComment: event.target.value })}
                                    value={this.state.movieComment}></textarea>
                            </div>

                            <div className='field'>Date watched
                                <DatePicker selected={this.state.startDate} onChange={(date) => this.setState({ startDate: date, movieWatched: date })} />

                            </div>

                            <button onClick={submitReview} className='ui button'>Submit</button>
                        </form>
                    </div>
                </div>
            </div>

        )

    }

}

export default CrudPost
hosssu
  • 1
  • 1
  • passing request body in GET method is a bad practice and Axios does not support it, read this [thread](https://stackoverflow.com/questions/54005520/sending-request-body-for-get-method-in-axios-throws-error) – username_jj Jul 22 '22 at 09:59

1 Answers1

0

GET requests should not have a body.

Change the method from 'GET' to 'POST'

or

use the params property

like so,

const res = await axios.get('http://localhost:3301/get', {
            params: {
                  username: this.state.username
            }
        })

For more reference -> Axios get in url works but with second parameter as object it doesn't

Mridul Gupta
  • 807
  • 1
  • 6
  • 8