无法 GET / 错误 - GET http://localhost:3000/ 404(未找到)
P粉236743689
P粉236743689 2024-03-27 14:13:04
0
1
362

使用 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粉236743689
P粉236743689

全部回复(1)
P粉738046172

当服务器接收到对其没有定义的处理程序 / 存在的路由的请求时,就会发生“无法获取 /”错误。

现在你有了这个:

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

    function sendData(request, response) {
      response.send(projectData);
    }
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板