NODE JS和JS,获取不到POST方法?

问题描述 投票:0回答:1

我正在尝试制作一个登录屏幕,但只有三个小时,我得到了一个“无法发布”的消息,我几乎要放弃了,然后我决定与你分享,我已经尝试了一切......这是我的代码:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const UserModel = require('../models/user.model');

const app = express();
app.route("url");

router.post('/login', async (req, res) => {
  const { userName, password } = req.body;

  try {
    // Procura um usuário com o userName informado
    const user = await UserModel.findOne({ userName });

    // Se não houver um usuário com o userName informado, retorna um erro
    if (!user) {
      return res.status(401).json({ message: 'Credenciais inválidas' });
    }

    // Compara a senha informada com a senha criptografada do usuário
    const isMatch = await bcrypt.compare(password, user.password);

    // Se as senhas não coincidirem, retorna um erro
    if (!isMatch) {
      return res.status(401).json({ message: 'Credenciais inválidas' });
    }

    // Se chegou até aqui, as credenciais estão corretas
    // e podemos armazenar o usuário na sessão
    req.session.user = user;

    // Redireciona o usuário para a página principal
    return res.redirect('/');
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: 'Erro interno do servidor' });
  }
});

module.exports = router;

所以,根据我们亲爱的 chatGPT,这应该是神奇的地方......我的意思是,身份验证会发生但不起作用,它返回我无法 POST 登录? 好吧,chatGPT 让我跑了好几圈……这是我的快递:

    const express = require("express");
    const UserModel = require("../src/models/user.model");
    const LocalStrategy = require('passport-local');
    const bcrypt = require('bcryptjs');
    const router = express.Router();
    const passport = require('passport');
    const bodyParser = require('body-parser')
    const session = require('express-session');
    const loginRouter = require('../src/auth/login');
    
    

    const app = express();
    app.use(session({
      secret: '12345678',
      resave: false,
      saveUninitialized: false,
    }));

    app.use(passport.initialize());
    app.use(passport.session());
    app.use('/login', loginRouter);


    router.get('/', (req, res) => {
      res.render('login');
    });
    
    router.post('/', async (req, res, next) => {
      passport.authenticate('local', function(err, user, info) {
        if (err) { return next(err); }
        if (!user) { return res.redirect('/login'); }
        req.logIn(user, function(err) {
          if (error) { return next(error); }
          return res.redirect('/');
        });
      })(req, res, next);
    });
    
    router.get('/logout', function(req, res){
      req.logout();
      res.redirect('/');
    });
    



    app.use(express.json());
    
    app.use(express.urlencoded({ extended: false }));

    app.set("view engine", "ejs");
    app.set("views", "src/views");

    app.use((req, res, next) => {
      console.log(`Request Type: ${req.method}`);
      console.log(`Content Type: ${req.headers["content-type"]}`);
      console.log(`Date: ${new Date()}`);

      next();
    });


    app.use(bodyParser.urlencoded({ extended: true }));

    app.use(require('express-session')({
      secret: 'my-secret-key',
      resave: false,
      saveUninitialized: false
    }));

    app.use(passport.initialize());
    app.use(passport.session());

    passport.use(require('../src/auth/login'));
    passport.serializeUser((user, done) => {
      done(null, user.id);
    });

    passport.deserializeUser(async (id, done) => {
      try {
        const user = await UserModel.findById(id);
        done(null, user);
      } catch (error) {
        done(error);
      }
    });

    app.use((req, res, next) => {
      res.locals.currentUser = req.user;
      next();
    });

    app.get('/', (req, res) => {
      res.render('../../src/views/first');
    });

    app.get("/views/users", async (req, res) => {
      const users = await UserModel.find({});

      res.render("index", { users });
    });

    app.get("/users/:userId/books/:bookId", async (req, res) => {
      try {
        const userId = req.params.userId;
        const bookId = req.params.bookId;

        const user = await UserModel.findById(userId);
        const book = user.books.find(book => book.bookId == bookId);

        if (!book) {
          return res.status(404).send("Livro não encontrado!");
        }

        res.render("book-details", { book });
      } catch (error) {
        return res.status(500).send(error.message);
      }
    });

    app.get("/users", async (req, res) => {
      try {
        const users = await UserModel.find({});

        res.status(200).json(users);
      } catch (error) {
        return res.status(500).send(error.message);
      }
    });

    app.get("/users/:id", async (req, res) => {
      try {
        const id = req.params.id;

        const user = await UserModel.findById(id);

        return res.status(200).json(user);
      } catch (error) {
        return res.status(500).send(error.message);
      }
    });

    app.post("/users", async (req, res) => {
      try {
        const user = await UserModel.create(req.body);

        res.status(201).json(user);
      } catch (error) {
        res.status(500).send(error.message);
      }
    });

    app.patch("/users/:id", async (req, res) => {
      try {
        const id = req.params.id;

        const user = await UserModel.findByIdAndUpdate(id, req.body, { new: true });

        res.status(200).json(user);
      } catch (error) {
        res.status(500).send(error.message);
      }
    });

    app.delete("/users/:id", async (req, res) => {
      try {
        const id = req.params.id;

        const user = await UserModel.findByIdAndRemove(id);

        res.status(200).json(user);
      } catch (error) {
        res.status(500).send(error.message);
      }
    });

    const port = 8080;

    app.listen(port, () => console.log(`Rodando com Express na porta ${port}!`));

最后,这是我的表单和我的 UserModel 文件,以防有人想知道他们拥有的用户定义,这样更容易看到:D

形式:

  <!DOCTYPE html>
  <html lang="en">
      
  <%-include('../views/partials/head.ejs')%>

  <style>

  @import url('https://fonts.cdnfonts.com/css/gotham');

      main{
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
      }
      #log-in{
          display:flex;
          position: absolute;
          margin-bottom: 280px;
      }
      #content{
          color: white;
          display: flex;
          flex-direction: column;
          margin-top: 300px;
          max-width: 700px;
          min-width: 520px;
          align-items: center;
          min-height: 380px;
          justify-content: center;
          background: linear-gradient(145deg, #3f3f3f, #353535);
  box-shadow:  41px 41px 100px #181818,
              -41px -41px 100px #5e5e5e;
              border-radius: 22px;
      }
      .login{
          margin: 20px;
          text-align: center;
          font-family: 'Gotham';
          border: none;
          columns: 1;
          justify-content: center;
          align-items: center;
          color: white;
          font-size: 18px;
          padding: 10px;
          display: flex;
          background-color: transparent;
          border-bottom: 1px solid white;
      }
      #login-button {
        
    --clr-font-main: hsla(0 0% 20% / 100);
    --btn-bg-1: rgb(135, 20, 20);
    --btn-bg-2: rgb(78, 6, 6);
    --btn-bg-color: rgb(255, 255, 255);
    --radii: 0.5em;
    cursor: pointer;
    padding: 0.9em 1.4em;
    min-width: 120px;
    min-height: 44px;
    font-size: var(--size, 1rem);
    font-family: "Gotham", system-ui, sans-serif;
    font-weight: 500;
    transition: 0.8s;
    background-size: 280% auto;
    background-image: linear-gradient(325deg, var(--btn-bg-2) 0%, var(--btn-bg-1) 55%, var(--btn-bg-2) 90%);
    border: none;
    border-radius: var(--radii);
    color: var(--btn-bg-color);
    box-shadow: 0px 0px 20px rgba(255, 71, 71, 0.5), 0px 5px 5px -1px rgba(233, 58, 58, 0.25), inset 4px 4px 8px rgba(255, 175, 175, 0.5), inset -4px -4px 8px rgba(216, 19, 19, 0.35);
    margin: auto;
          display: flex;
          text-align: center;
          align-items: center;
  }

  #login-button:hover {
    background-position: right top;
  }

  #login-button:is(:focus, :focus-within,:active) {
    outline: none;
    box-shadow: 0 0 0 3px var(--btn-bg-color), 0 0 0 6px var(--btn-bg-2);
  }

  @media (prefers-reduced-motion: reduce) {
    #login-button {
      transition: linear;
    }
  }

  </style>

  <body>

      <main>
          <div id="content">
              <h1 id="log-in">Loja de livros online</h1>
              <form method="post" action="./login.js">
                
                  <input placeholder="Usuário" class="login" type="text" name="login" id="login">
                  <br>

                  <input placeholder="Senha..." class="login" type="password" name="password" id="password">
                  <br>
                  <button id="login-button" type="submit">Logar</button>
              </form>
          </div>
      </main>

  </body>
  </html>

和用户模型:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
    minlength: 7,
  },
    books: [{
      bookId: {
        type: Number,
        unique: true
      },
      bookName: {
        type: String,
        required: true
      },
      bookPrice: {
        type:Number,
        required: true
      },
      bookDescription: {
        type: String,
        required: true
      },
      bookAuthor:{
        type: String,
        required: true
      }   
    }]
});

userSchema.pre('save', function (next) {
  let highestBookId = 0;
  this.books.forEach((book) => {
    if (book.bookId > highestBookId) {
      highestBookId = book.bookId;
    }
  });

  let nextBookId = highestBookId + 1;
  this.books.forEach((book) => {
    if (!book.bookId) {
      book.bookId = nextBookId;
      nextBookId++;
    }
  });

  next();
});

const UserModel = mongoose.model("User", userSchema);

module.exports = UserModel;

  

我希望我的登录屏幕至少可以工作,这个 API 的其余部分工作正常,它只是涉及登录和......我在几分钟内使用我的 VSCode 搞砸了整个应用程序

javascript node.js mongodb express ejs
1个回答
0
投票

您的表单操作指向文件,而不是 Express 路由。如果你想在

'/'
路由中处理登录内容,那么需要相应地设置 HTML 文件中的操作:
<form method="post" action="/"> 

© www.soinside.com 2019 - 2024. All rights reserved.