繁体   English   中英

Node.js/Express 发布路由失败

[英]Node.js/Express post route failing

第一次试用 Node.js。 我的 POST 路线因“无法 POST /admin/add-product.html”而失败。 GET 请求从同一条路线上得到了很好的服务。 我已经看过这里了。 类似问题的几个答案,但没有任何帮助。 这是我的代码:

./index.js

const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

const adminRoutes = require('./src/routes/admin');
const shopRoutes = require('./src/routes/shop');

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

app.use('/admin', adminRoutes);
app.use(shopRoutes);

app.listen(3000);`

./src/routes/admin.js

const path = require('path');

const express = require('express');

const router = express.Router();

// served on /admin/add-product GET route
router.get('/add-product', (req, res, next) => {
  res.sendFile(path.join(__dirname, '../', 'views', 'add-product.html'));
});

// served on /admin/add-product POST route
router.post('/add-product', (req, res, next) => {
  console.log(req.body);
  res.redirect('/');
  // res.send('<h1>product saved</h1>');
});

module.exports = router;

./src/views/add-product.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Add Product</title>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li><a href="/">Shop</a></li>
          <li><a href="add-product">Add Product</a></li>
        </ul>
      </nav>
    </header>
    <main>
      <form action="/admin/add-product.html" method="POST">
        <input type="text" name="title" /><button type="submit">
          Add Product
        </button>
      </form>
    </main>
  </body>
</html>

谢谢!!!

表单中的动作需要与 NodeJS 应用中的路由声明相匹配,应该是:

<form action="/admin/add-product" method="POST">

从表单的 action 属性中删除 .HTML。

暂无
暂无

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

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