不能获取 / 错误 – 获取 http://localhost:3000/ 404 (未找到)

huangapple go评论54阅读模式
英文:

Cannot GET / error - GET http://localhost:3000/ 404 (Not Found)

问题

我在使用Node和Express.js时在浏览器上收到了"Cannot GET /"的错误。从控制台上我得到了以下信息:Failed to load resource: the server responded with a status of 404 (Not Found)。以下是服务器和浏览器的代码。我真的需要帮助,因为我无法理解这段代码有什么问题。基本上,我正在参加Udacity的前端开发纳米学位课程,我正在按照练习进行。这个练习我无法让它工作。

服务器的代码:

/* 用作所有路由的端点的空JS对象 */
projectData = {};

/* 使用Express运行服务器和路由 */
const express = require("express");

/* 启动应用程序的实例 */
const app = express();

/* 依赖项 */
const bodyParser = require("body-parser");

/* 中间件 */
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require("cors");
app.use(cors());

/* 初始化主项目文件夹 */
app.use(express.static("website"));

const port = 3000;
/* 启动服务器 */
const server = app.listen(port, listening);
function listening() {
  // console.log(server);
  console.log(`在localhost上运行:${port}`);
}

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

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

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

function callBack(req, res) {
  res.send("已收到POST请求");
}

// POST一个动物
const data = [];

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

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

浏览器的代码:

/* 用于POST数据的函数 */
const postData = async (url = "", data = {}) => {
  console.log(data);
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, 等等
    credentials: "same-origin", // 包括,*same-origin,omit
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data), // body数据类型必须与"Content-Type"标头匹配
  });

  try {
    const newData = await response.json();
    // console.log(newData);
    return newData;
  } catch (error) {
    console.log("错误", error);
    // 适当处理错误
  }
};

// 调用函数
postData("addAnimal", { animal: "狮子" });
英文:

I am getting the "Cannot GET /" on my browser when using node and express.js. From the console I get: Failed to load resource: the server responded with a status of 404 (Not Found). The following code is for both the server and browser. I really need some help as I cannot understand what is wrong with this code. Bascially I am taking a nanodegree in front end development with Udacity and I am following the exercises. This exercise I couldn't make it work.

    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" });

答案1

得分: 1

"Cannot GET /"错误是在服务器收到对未定义处理程序的路由的请求时发生的,或者路由不存在。

现在你有这个:

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

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

这意味着如果你想使用GET获取所有动物,你需要发送"/all"而不是"addAnimal"。在你的示例代码中,你写的是POST而不是GET

"addAnimal"甚至不是一个路由。接近的路由是"/animal"。我认为你正在查看函数名称,而不是路由名称。

  • GET = "/all"
  • POST = "/add"
  • POST = "/animal"

我不确定你的设置是否正确。它可能能够工作,但我会这样做:

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();
const port = 3000;

// Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(express.static("website"));

// 路由
const router = express.Router();

// GET 路由
router.get("/all", (req, res) => {
  res.send(projectData);
});

// POST 路由
router.post("/add", (req, res) => {
  res.send("POST received");
});

// POST 一个动物
const data = [];

router.post("/animal", (req, res) => {
  data.push(req.body);
});

// 挂载路由
app.use(router);

// 启动服务器
app.listen(port, () => {
  console.log(`服务器正在运行,地址为 http://localhost:${port}`);
});

在我的示例中,路由是使用express.Router()定义的。然后,我删除了projectData,因为在服务器端代码中避免使用全局变量通常更好,并且代码更易于阅读和理解。

因此,URL 将如下所示:

  • http://localhost:3000/all
  • http://localhost:3000/add
  • http://localhost:3000/animal

这是我如何获取所有动物的方式(GET):

fetch('/all')
  .then(response => response.json())
  .then(data => {
    // 处理接收到的数据
    console.log(data);
  })
  .catch(error => {
    // 处理任何错误
    console.error('错误:', error);
  });

或者也许你更喜欢这种方式(POST):

const postData = async (url = "", data = {}) => {
  console.log(data);
  const response = await fetch(url, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  try {
    const newData = await response.text();
    // 处理响应数据
    console.log(newData);
    return newData;
  } catch (error) {
    // 处理任何错误
    console.error("错误:", error);
  }
};

// 用法示例
const exampleData = { example: "data" };
postData("/add", exampleData);

如果你想知道如何发送回你发送的内容,可以这样做:

const postData = async (url = "", data = {}) => {
  const response = await fetch(url, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });

  try {
    const responseData = await response.json(); // 将响应数据解析为 JSON
    console.log(responseData); // 显示接收到的数据
    return responseData;
  } catch (error) {
    console.error("错误:", error);
  }
};

const animalData = { animal: 'lion' };
postData("/animal", animalData);

// POST 一个动物
router.post("/animal", (req, res) => {
  data.push(req.body);
  const animal = req.body; // 从请求体中获取动物数据
  res.send(animal); // 将接收到的动物数据作为响应发送回去
});

我通常这样思考:

  • req = 请求(用户请求/发送的内容)
  • res = 响应(对请求的答复,我们发送回去的内容)
英文:

The "Cannot GET /" error occurs when the server receives a request for a route that it doesn't have a defined handler for / exist.

Now you have this :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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

<!-- end snippet -->

Which means if you want to get all animal with the GET you have to send in &quot;/all&quot; not &quot;addAnimal&quot;. And in your example code you have written it to do a POST not a GET.

The &quot;addAnimal&quot; is not even a route. Close one is &quot;/animal&quot;. I think you are looking at the function names as you have a function called addAnimal instead of the routes names.

GET = &quot;/all&quot;
POST = &quot;/add&quot;
POST = &quot;/animal&quot;

And I'm not sure if you setup is correct. It probably works but I would have done something like this:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const express = require(&quot;express&quot;);
const bodyParser = require(&quot;body-parser&quot;);
const cors = require(&quot;cors&quot;);

const app = express();
const port = 3000;

// Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(express.static(&quot;website&quot;));

// Routes
const router = express.Router();

// GET route
router.get(&quot;/all&quot;, (req, res) =&gt; {
  res.send(projectData);
});

// POST route
router.post(&quot;/add&quot;, (req, res) =&gt; {
  res.send(&quot;POST received&quot;);
});

// POST an animal
const data = [];

router.post(&quot;/animal&quot;, (req, res) =&gt; {
  data.push(req.body);
});

// Mount the router
app.use(router);

// Start the server
app.listen(port, () =&gt; {
  console.log(`Server is running on http://localhost:${port}`);
});

<!-- end snippet -->

In my example the routes are defined using express.Router(). Expressjs Routing And then I removed the projectData as it's generally better to avoid using global variables in server-side code. And its much easier to read and follow along in the code.

So this will be :

GET /all: Retrieves and sends the projectData object as a response.

POST /add: Sends a simple &quot;POST received&quot; response.

POST /animal: Pushes the request body into the data array.

So the URL will be the following :

http://localhost:3000/all, http://localhost:3000/add, http://localhost:3000/animal.

This is how I would get all animals (GET):
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

fetch(&#39;/all&#39;)
  .then(response =&gt; response.json())
  .then(data =&gt; {
    // Handle the received data
    console.log(data);
  })
  .catch(error =&gt; {
    // Handle any errors
    console.error(&#39;Error:&#39;, error);
  });

<!-- end snippet -->

Or maybe you prefer it like this (POST) :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const postData = async (url = &quot;&quot;, data = {}) =&gt; {
  console.log(data);
  const response = await fetch(url, {
    method: &quot;POST&quot;,
    credentials: &quot;same-origin&quot;,
    headers: {
      &quot;Content-Type&quot;: &quot;application/json&quot;,
    },
    body: JSON.stringify(data),
  });

  try {
    const newData = await response.text();
    // Handle the response data
    console.log(newData);
    return newData;
  } catch (error) {
    // Handle any errors
    console.error(&quot;Error:&quot;, error);
  }
};

// Usage example
const exampleData = { example: &quot;data&quot; };
postData(&quot;/add&quot;, exampleData);

<!-- end snippet -->

Let me know if there's something I can further explain.

Update as you ask in the comment how to send back the one you are sending you can do this :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const postData = async (url = &quot;&quot;, data = {}) =&gt; {
  const response = await fetch(url, {
    method: &quot;POST&quot;,
    credentials: &quot;same-origin&quot;,
    headers: {
      &quot;Content-Type&quot;: &quot;application/json&quot;,
    },
    body: JSON.stringify(data),
  });

  try {
    const responseData = await response.json(); // Parse the response data as JSON
    console.log(responseData); // Display the received data
    return responseData;
  } catch (error) {
    console.error(&quot;Error:&quot;, error);
  }
};

const animalData = { animal: &#39;lion&#39; };
postData(&quot;/animal&quot;, animalData);

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// POST an animal

router.post(&quot;/animal&quot;, (req, res) =&gt; {
  data.push(req.body);
  const animal = req.body; // Get the animal data from the request body
  res.send(animal); // Send the received animal data back as the response
});

<!-- end snippet -->

I usually think like this :

req = Request (What are the user requesting / sending)

res = Response (What's the answer to that request, what are we sending back)

huangapple
  • 本文由 发表于 2023年5月29日 01:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定