Unable to GET / Error - GET http://localhost:3000/ 404 (Not Found)
P粉236743689
P粉236743689 2024-03-27 14:13:04
0
1
325

I'm getting a "Unable to get /" message on my browser when using Node and express.js. From the console I get: Unable to load resource: The server responded with a status of 404 (Not Found). The following code works on both server and browser. I really need some help as I can't understand what's wrong with this code. Basically, I'm doing a front-end development nanodegree at Udacity and I'm following the exercises. I didn't succeed with this exercise.

Code for the server:
    /* Empty JS object to act as endpoint for all routes */
    projectData = {};

    /* Express to run server and routes */
    const express = require("express");

    /* Start up an instance of app */
    const app = express();

    /* Dependencies */
    const bodyParser = require("body-parser");
    /* Middleware*/
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    const cors = require("cors");
    app.use(cors());

    /* Initialize the main project folder*/
    app.use(express.static("website"));

    const port = 3000;
    /* Spin up the server*/
    const server = app.listen(port, listening);
    function listening() {
      // console.log(server);
      console.log(`running on localhost: ${port}`);
    }

    // GET route
    app.get("/all", sendData);

    function sendData(request, response) {
      response.send(projectData);
    }

    // POST route
    app.post("/add", callBack);

    function callBack(req, res) {
      res.send("POST received");
    }

    // POST an animal
    const data = [];

    app.post("/animal", addAnimal);

    function addAnimal(req, res) {
      data.push(req.body);
    }

   code for the browser
  /* Function to POST data */
  const postData = async (url = "", data = {}) => {
    console.log(data);
    const response = await fetch(url, {
      method: "POST", // *GET, POST, PUT, DELETE, etc.
      credentials: "same-origin", // include, *same-origin, omit
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data), // body data type must match "Content-Type" header
    });

    try {
      const newData = await response.json();
      // console.log(newData);
      return newData;
    } catch (error) {
      console.log("error", error);
      // appropriately handle the error
    }
  };

  //Call Function
  postData("addAnimal", { animal: "lion" });

P粉236743689
P粉236743689

reply all(1)
P粉738046172

The "Unable to get /" error occurs when the server receives a request for a route for which no defined handler / exists.

Now you have this:

    // GET route
    app.get("/all", sendData);

    function sendData(request, response) {
      response.send(projectData);
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template