Home > Net >  Error "Cannot GET /", React.js Express.js
Error "Cannot GET /", React.js Express.js

Time:01-21

Hey guys I did a project that simulates Netflix and I'm making it using react for the front end and Node.js express.js for the Back end. When I run the react code, the paths of each page are working. What I mean when I say "paths" is paths like "http://localhost:3000/" and "http://localhost:3000/login". However, when I start running the server-side code and then I refresh the page, I get this message: "Cannot GET /" or "Cannot GET /login". I think I have a problem about handling the GET request on my server, but my POST requests are handled pretty well. I will provide you my home page code component and login page code component and server-side code, Also App component code and project file structure below:

(react code)home page:

import React,{useState} from 'react';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import InfoIcon from '@mui/icons-material/Info';
import Header from './header.jsx';
import Footer from './footer.jsx';

import List from './list.jsx';
import axios from "axios";
import { useEffect } from 'react';



export default function Home(){
    const[movies,SetMovies] = useState([]); 
    const[randomPoster,SetrandomPoster] = useState({}); 
    const type="";

    useEffect(()=>{
        const fetch = async()=>{
         await axios.get("https://api.themoviedb.org/3/movie/upcoming?api_key=c2ca0c1d4432e9a9db70a5b7154e2053").then(async data=> {  const d = await data.data.results; SetMovies(d)}).catch(err =>  console.log(err));

        }

        fetch();

    },[]);


            const fetch2 =  async()=>{
                const index = Math.round(Math.random() * movies.length-1);
            let r =   movies[2];
          

            const image = "https://image.tmdb.org/t/p/w500"  r.backdrop_path    

            return {image :image, title: r.title, overview: r.overview}
         }

         const temp =  fetch2();

         temp.then(async res=>{
             SetrandomPoster(res);
            
         })



    return(
        <>
        <Header/> 
    <div className='home'>
        <div className='imgStuff'>
        {type&&( <>
        <div id='genre'>
         <h1>{type}</h1>
        <select > 
        <option value=""></option>
        <option value=""></option>
        <option value=""></option>

        </select>
        </div>
        </>)}
    <img className= "poster" src={randomPoster.image} alt="" />

    <div className='texts'>

        <div className='title'>
        <h1>Watch {randomPoster.title}</h1>
        <h3>{randomPoster.overview}</h3>
        </div>
        <div className='btns'>
        <button className='Playbtn'><PlayArrowIcon id= "play"/>Play</button>
        <button className='Infobtn'><InfoIcon id = "info"/>Info</button>
        </div>
        </div>
    </div>
        <List name="Popular"/>
        <List name="Trending"/>
        <List  name="Comingup"/>
        <List  name="Playing now"/>
        
    </div>
   

    <Footer/>
    </>
        
    );



}

(react code)login page:

import React, { useState } from "react";
import LoginHeader from './LoginHeader';

export default function Login(){
  // useState hook to store the input values
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const handlePost = () => {
    fetch('http://localhost:3000/login', {
        method: "POST",
        headers: {
          'Content-type': 'application/json'
        },
        body: {
            username: username,
            password: password
        }
      })
      .then((response) => response.json())
      .then((result) => {
        console.log(result)
      })};

  return (
    <>
      <LoginHeader/>
      <div className="login">
        <div className="formContainer">
          <form className="form"  onSubmit={handlePost}>
            <h2 className="textSginin">Sign in</h2>
            <div >
              <input className="username" type="text" onChange={(e) => setUsername(e.target.value)}/>
              <input className ="password"type="password" onChange={(e) => setPassword(e.target.value)}/>
            </div>
            <div className="buttonContainer">
              <input id="submit" type="submit" value={"login"}/>
              <div className="spanFlex">
                <div className="checkboxContainer">
                  <input id = "checkbox" type="checkbox"/>Remeber me?
                </div>
                <span id="help">Need help?</span>
              </div>
            </div>
          </form>
          <div className="signupAlert" >
            <h2>New to Netflix? <span>Sign up now.</span></h2>
            <p>This page is protected by Google reCAPTCHA to ensure you're not a bot. <span>Learn more.</span></p>
          </div>
        </div>
      </div>
    </>
  );
}

server-side:

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();

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

app.post("/login", (req,res)=>{
    const username = req.body.username;
    const password =  req.body.password;


    console.log(username  " "  password);
    res.status(200).send("ok");
})

app.listen(3000,()=>{
    console.log("server connected on port 3000");
})

App component code

import '../style/App.css';
import { BrowserRouter as Router, Routes , Route } from "react-router-dom";

import Home from './home.jsx';
import Login from './login'
import React from 'react';



function App() {

  return(
      <div>
     
   
   


     <Router>
        <Routes >
          <Route path="/" exact element={<Home/> } />
          <Route path="/login" element={ <Login/>} />
        </Routes >
      </Router>
    </div>
  );
}

export default App;

Project file structure

Project file structure

CodePudding user response:

GET method for different route(s) is not defined in server side. Or if you have defined please share that code too. Below is just an example how you can define(if not defined already).

app.get("/login", (req,res)=>{
// logic
})
app.get("/", (req,res)=>{
// logic
})

CodePudding user response:

I guess my mistake was running the react project and the server on the same port 3000, I have fixed that by running the server code on other port like 3001

  • Related