简体   繁体   English

连接到路由的表单操作问题(Nodejs,Express)

[英]Issue with form action to connect to routing (Nodejs, Express)

I have a nodejs project using Express.我有一个使用 Express 的 nodejs 项目。 I have had a problem, and after hours and hours I figured out what it is, but I don't know how to fix it.我遇到了一个问题,几个小时后我弄清楚它是什么,但我不知道如何解决它。

I have a form that I want to submit to a database, but the form action="" is not finding the correct route, I think.我有一个要提交到数据库的表单,但我认为表单 action="" 没有找到正确的路径。

Everything works in my entire project, all pages that are NOT in nested directories like add-shop.ejs below.一切都在我的整个项目中工作,所有不在嵌套目录中的页面,如下面的 add-shop.ejs。 They post data fine.他们发布数据很好。 I also did a test on the router我也在路由器上做了个测试

I am going to to list my directory structure我要列出我的目录结构

| public
| models
         | shopModel.js
| routes
         | shop.js
         | index.js
| views
         | shop
                | add-shop.ejs
         | index.ejs
         | contact.ejs
| app.js

My form in views/shop/add-shop.ejs with the form action我在views/shop/add-shop.ejs 中的表单与表单操作

<form action="/add-shop" method="post" class="post-form">
  <form stuff to do>
</form>

My app.js (just the route setting, I commented above it)我的 app.js (只是路由设置,我在上面评论过)

const mainRoutes = require('./routes');
app.use(mainRoutes);

//This is the routes for shop route
const shopRoutes = require('./routes/shop.js');
app.use(shopRoutes);

My route: routes/shop.js我的路线:routes/shop.js

const express = require('express');
const router = express.Router();
const Shops = require('../models/shopModel.js');

router.get('/add-shop', (req, res) => {
    //getting the page successfully
});

router.post(('/add-shop', (req, res) => {
    //adding stuff not so successfully
}));

module.exports = router;

I keep getting a 404 error after sending the form, that it can't find the page /add-shop even though I am sending the form from /add-shop page?发送表单后我一直收到 404 错误,即使我从 /add-shop 页面发送表单,它也找不到页面 /add-shop? Is it because of the directory structure?是因为目录结构吗?

You have one pair of brackets too much in your code你的代码中有太多的括号

router.post(('/add-shop', (req, res) => {
    //adding stuff not so successfully
}));

needs to be需要是

router.post('/add-shop', (req, res) => {
    //adding stuff not so successfully
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM