简体   繁体   中英

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

I have a nodejs project using Express. 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.

Everything works in my entire project, all pages that are NOT in nested directories like add-shop.ejs below. 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

<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)

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

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? 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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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