首页 > 解决方案 > 尽管存在路线,但未捕获 JADE 表单提交

问题描述

我正在使用 JADE、node.js 和 express 创建一个表来选择一些数据。一切都在本地主机上运行。当我尝试路由 /climateParamSelect 时,它可以工作并显示我希望看到的内容,包括 URL 编码元素。

路由到此代码片段在 app.js 中,但我确认它使用 /climateParamSelect?test=test 有效。路线位于climateParamSelect.js

router.get('/', async function(req, res, next) {
    console.log('GET');
    console.log(req.query);
});

router.post('/', async function(req, res, next) {
    console.log('POST');
    console.log(req.params);
});
module.exports = router;

app.js 中的代码毕竟可能很重要,所以这里摘录:

const express = require('express');
var tableSelectRouter = require('./routes/tableSelect');
var cpSelectRouter = require('./routes/climateParamSelect');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/climateParamSelect', cpSelectRouter);
app.use('/tableSel', tableSelectRouter);

当我使用下一页的提交按钮时,它被调用但由于某种原因,上面的路线从未被采用。相反,它显示:等待本地主机。

html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    link(rel='stylesheet', href='https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css')
    script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js')  
    script(src='https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js')  
    script.
        $(document).ready(function() {
            $('#selTable').DataTable();
        });
body
  form(name='productionSelect', method='post', action='/climateParamSelect')
    div#wrapper
      h1 Select production data for feature generation
      br
      table#selTable.display
        thead
          tr
            th headers
            //... 
        tbody
          tr
            td 
              input(type='checkbox',id='#{r}',name='#{r}')
            td 
            //...   
      br
      input(type='submit',value='Select Production',name='prodSubmit',data-transition='fade', data-theme='c')

我在这里想念什么?

谢谢

标签: javascriptnode.jsexpresspug

解决方案


浏览器将在那里旋转,直到它收到响应,并且在您的路由中没有发送响应。我确定你会想要渲染一个视图,但要快速测试它,只需使用res.send一个字符串。

第二个问题是您如何读取从客户端发送的数据。 req.params用于使用路由中的变量进行动态 URL 解析。要处理表单数据(这是您在此处发送的数据),您可以使用req.body.

更改您的路线应该可以解决您的问题:

router.post('/climateParamSelect', async function(req, res, next) {
    console.log('POST');
    console.log(req.body);
    res.send("hello");
});

推荐阅读