搜尋

首頁  >  問答  >  主體

無法 GET / 錯誤 - GET http://localhost:3000/ 404(找不到)

使用 Node 和express.js 時,我在瀏覽器上收到「無法取得/」的訊息。從控制台我得到: 無法載入資源:伺服器回應狀態為 404(未找到)。以下程式碼適用於伺服器和瀏覽器。我真的需要一些幫助,因為我無法理解這段程式碼有什麼問題。基本上,我正在 Udacity 攻讀前端開發奈米學位,並且正在遵循練習。這個練習我沒能成功。

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粉236743689P粉236743689271 天前356

全部回覆(1)我來回復

  • P粉738046172

    P粉7380461722024-03-28 00:09:55

    當伺服器接收到對其沒有定義的處理程序 / 存在的路由的請求時,就會發生「無法取得 /」錯誤。

    現在你有了這個:

        // GET route
        app.get("/all", sendData);
    
        function sendData(request, response) {
          response.send(projectData);
        }

    回覆
    0
  • 取消回覆