简体   繁体   English

错误“无法获取/”,React.js+ Express.js

[英]Error "Cannot GET /", React.js+ Express.js

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.大家好,我做了一个模拟 Netflix 的项目,我在前端使用 react,在后端使用 Node.js express.js。 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".当我说“路径”时,我的意思是像“http://localhost:3000/”和“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".但是,当我开始运行服务器端代码然后刷新页面时,我收到此消息:“Cannot GET /”或“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.我想我在处理服务器上的 GET 请求时遇到了问题,但我的 POST 请求处理得很好。 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:我将提供我的主页代码组件和登录页面代码组件和服务器端代码,以及 App 组件代码和项目文件结构如下:

(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项目文件结构

项目文件结构

GET method for different route(s) is not defined in server side.服务器端未定义不同路由的GET方法。 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 })

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我想我的错误是在同一个端口 3000 上运行反应项目和服务器,我已经通过在其他端口(如 3001)上运行服务器代码来解决这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM