node.js - 在通过 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" 的表单
解决方案
推荐阅读
- kubernetes - 匿名访问 Kibana Dashboard(K8s 集群)
- html - 台式机和平板电脑或智能手机中的不同布局行为
- loopbackjs - 环回更新模型扩展自用户模型错误
- json - 尝试使用类型“FolderBasedDartSdk”作为函数
- javascript - 聚合物纸输入 - 启用 ios 选项卡箭头
- docker - 尝试运行容器时,docker 是否需要额外的端口?
- mysql - Postgres乘法函数添加到带有数据库触发器的字段
- ajax - 如何在 Wordpress 中使用 Ajax 获取高级自定义字段值
- javascript - 如何从 Android 创建 webScoket 服务器,该服务器可以与在我的 android web 视图中呈现的这个 JS 代码进行通信
- spring - 如何使用 JOOQ 和 Spring-boot 2.0 进行手动事务管理?