Home > Net >  "Cannot GET /" error while running API call
"Cannot GET /" error while running API call

Time:06-13

I am running this API but getting "Cannot Get/" error. I am submitting a form on myfrontend (localhost:3000) and my backend is hosted on localhost:8000. The post URL is set to backend URL i.e port 8000. So why am I unable to post data into port 8000 and get a response. What am I doing wrong here? Plz help.

Code on front end(React):

import Navi from "./nav"
import "../node_modules/bootstrap/dist/css/bootstrap.css";
import { useState } from "react";
import axios from "../node_modules/axios/dist/axios";

const Home = () => {

    const [Email, setEmail]=useState(" ");
    const [Password, setPassword]=useState(" ");
    return(
        <>
        <Navi/>
        <h1 className="registerheading">Register</h1>
<form>
    <div>
        <label> Email</label>
        <input 
        type="email"
        value={Email}
        onChange={(e) => {
            e.preventDefault();
            setEmail=(e.target.value);
            console.log(setEmail);
        }}
        /> 
    </div>
    <div>
        <label>Password</label>
        <input 
        type="password"
        value={Password}
        onChange={(e) => {
            e.preventDefault();
            setPassword=(e.target.value);
            console.log(setPassword);
        }}
        /> 
    </div>
    <div>
        <button 
        type="submit"
        onClick={(e) => {
            e.preventDefault();
           axios.post("http://localhost:8000")
            .then(()=>{console.log("request sent")})
            .catch((error) =>{error});
        }}
        > Submit</button>
    </div>
  </form> 
        </>
    )
}
export default Home;

Code on backend(Node.js):

import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import DB from "./env";
const app = express();
app.use(express.json({}));
app.use(cors({
    origin:["http://localhost:3000"],
}));

app.post("http://localhost:8000" , (req,res) => {
    res.end("done");
})
app.listen(8000);

CodePudding user response:

The following line

app.post("http://localhost:8000" , (req,res) => {
    res.end("done");
})

change to

app.post("/" , (req,res) => {
    res.end("done");
})

Recommended Read: Expressjs Routing

CodePudding user response:

I think you should change the url given in app.post in backend

Change this

app.post("http://localhost:8000" , (req,res) => {
    res.end("done");
})

To this

app.post("/" , (req,res) => {
        res.end("done");
    })
  • Related