首页 > 解决方案 > Node.js 中的路由

问题描述

我在 Node.js 有一个项目。我需要将表单的信息发送到后端。信息已发送,但它显示给我undefined。这是怎么回事?

我的代码:

添加一个新的“时间”


document.addEventListener("DOMContentLoaded", () => {
  atualizarTime();
})

function atualizarTime() {

  fetch("http://localhost:3000/router/times")
    .then(res => {
      // É necessário converter a resposta do fethc para JSON. Para podermos trabalhar
      // Com as informações vindas do servidor.
      return res.json();
      
    })
    .then(data => { // Retorna os dados da API.

      let timeElements = "";
      let times = JSON.parse(data);

      times.forEach((time) => {

        let timeElement = 
          `
          <div class="time">
            <h1>Nome do time: ${time.nome}</h1>
            <h3>Email do time: ${time.email}</h3>
            <hr>
          </div>
        `;

        timeElements += timeElement;
      });

      document.getElementById("sectionContainerTimesInfo").innerHTML = timeElements;

    })

}

我的 server.js:


const PORT = 3000;
const express = require("express");
const app = express();
const router = require("./routes/router");
const path = require("path");

app.use("/router", router);
app.use("/", express.static(path.join(__dirname, "public")));
app.use("/times", express.static(path.join(__dirname, "public/pages/times")));

app.listen(PORT, () => console.log("Server running in port 3000"));

路线.js:


const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const timesParticipantes = require("../model/timesParticipantes");

router.use("/", bodyParser.json());

router.get("/times", (req, res) => {
  res.json(JSON.stringify(timesParticipantes.pegarTodos()));
})

router.post("/", (req, res) => {
  const time = req.body.time;
  const email = req.body.email;

  timesParticipantes.novaInscricao(time, email);
  res.send("Time cadastrado!");
});

module.exports = router;

最后是我的表单 HTML:


<form action="/times">
            <div class="inputContainer">
              <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24"
                class="Input_icon__25hZg" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z">
                </path>
              </svg>

              <input 
                type="text"
                id="time"
                name="time"
                placeholder="Time" 
                required
              >
            </div>

            <div class="inputContainer">
              <svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 24 24"
                class="Input_icon__25hZg" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z">
                </path>
              </svg>

              <input 
                type="email" 
                id="email"
                name="email"
                placeholder="Email"
                required
              >
            </div>
            
            <div class="buttonSubscription">
              <button onclick="cadastrarTime()">Quero me inscrever!</button>
            </div>
          </form>

标签: javascripthtmlnode.jsexpress

解决方案


推荐阅读