>  Q&A  >  본문

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粉236743689206일 전288

모든 응답(1)나는 대답할 것이다

  • P粉738046172

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

    서버가 핸들러 / 존재가 정의되지 않은 경로에 대한 요청을 수신하면 "/를 가져올 수 없습니다" 오류가 발생합니다.

    이제 다음이 제공됩니다:

    으아악

    회신하다
    0
  • 취소회신하다