首页 > 解决方案 > 在通过 POST 方法提交我的表单时,它不会发布路由,而是会发送到我的获取请求

问题描述

我刚开始学习 Mongoose + Express 所以我在路由方面遇到了一些问题 我基本上是在尝试使用 express 和 mongoose 作为数据库来制作一个farmStand

这是我的主要 index.js

  const express = require('express');
    const app = express();
    const path = require('path')
    const Product = require('./models/product')
    
    
    const mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/farmStand', {useNewUrlParser: true, useUnifiedTopology: true})
    .then(()=>{
        console.log('Mongo Connection open!!!');
    })
    .catch(err=>{
        console.log('Oh no Mongo Error!!')
        console.log(err)
    })
    
    app.set('views',path.join(__dirname,'views'));
    app.set('view engine','ejs');
    app.use(express.urlencoded({extended:true}))
    
    app.get('/products',async (req,res)=>{
        const products = await Product.find({})
        res.render('products/index',{products});
    })
    
    app.get('/products/new', (req,res)=>{
        res.render('products/new')
    })
    
    app.post('/products',async (req,res)=>{
        const newProduct = new Product(req.body);
        await newProduct.save();
        res.redirect(`/products/${newProduct._id}`);
    })
    
    app.get('/products/:id',async (req,res)=>{
        const{id} = req.params;
        const product = await Product.findById(id);
       // console.log(product);
        res.render('products/show',{product})
    })
    
    
    
    // app.post('/products')
    
    
    app.listen(3000,()=>{
        console.log('App litsening on Port 3000!!!');
    })

我的 new.ejs 文件位于文件夹 views/products/new.ejs

它包含带有 method="POST" 和 action="/products" 的表单

标签: node.jsformsexpressmongoose

解决方案


推荐阅读