提交开机自检表单时出现"错误请求"



index.html中,有一个表单,一旦提交,应该重定向到results.html,以根据表单提交呈现一些信息。但是,我一直得到Bad RequestHTTP响应,并在SO上使用其他解决方案给我Cannot POST

当所有路由器都在app.js文件中时,这是有效的。现在,我已经为每个页面分离了路由,现在我无法访问/results.在此之前,表单(在/上)向/提交了POST请求,然后重定向到/results,但我正在尝试直接重定向到/results

索引.js:

router.get('/', function (req, res)  {
res.sendFile('/public/pages/index.html', {root: './'});
});

结果.js(我导入模块搜索并调用函数来渲染内容):

router.post('/', search.issues, function(req, res) {
console.log("In results");
let searchResult = req.body.searchResult;
res.render('results.html', {
results : searchResult.length,
searchTerm : req.body.searchTerm,
searchResult : searchResult,
category : req.body.category
});
});

app.js,我在其中导入和使用路由器:

/** begin importing all routes */
const indexRoute = require('./api/routes/index'),
aboutRoute = require('./api/routes/about'),
resultsRoute = require('./api/routes/results');
/** begin middleware use for routes */
app.use('/', indexRoute);
app.use('/about', aboutRoute);
app.use('/results', resultsRoute);

索引.html形式:

<form method="post" action="/results">

我应该被重定向到结果.html渲染,但我得到一个Bad Request的HTTP代码。我的路线在src/routes/results.htmlsrc/viewsindex.htmlsrc/public/pages/index.html.

你应该使用body-parser,因为默认情况下express不知道如何处理json文件,你应该使用express.static来提供你的html文件。

这是我将html文件夹的内容映射到本地主机:5000/。因此,您可以将表单.html文件放在此文件夹中并从localhost:5000/form.html访问它。

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var routes = require('./routes');
app.use('/', express.static('html'));
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
//Initilizing routes.
routes(app);

app.listen(5000, () => {
console.log("Listening on port 5000");
}); 

然后在您的路由中.js文件:

var routesAPI = function(app){
app.get('/product'), function (req, res) {   
console.log("GET products route");
}
app.post('/products', function (req, res) {
let product = req.body;
console.log(product);
res.json(product);
});
}
module.exports = routesAPI;

请更改路由器顺序,

app.use('/about', aboutRoute);
app.use('/results', resultsRoute);
app.use('/', indexRoute);

默认情况下,任何路由都在访问/路由。

最新更新