簡體   English   中英

POST表單提交中的“錯誤請求”

[英]'Bad Request' on POST form submission

index.html有一種表單,一旦提交,應將其重定向到results.html以基於表單提交呈現一些信息。 但是,我不斷收到Bad Request HTTP響應,並在SO上使用其他解決方案使我Cannot POST

當所有路由器都在app.js文件中時,此方法有效。 現在,我已經為每個頁面分隔了路由,現在我無法達到/results 在此之前,該形式(這是/ )提交了POST請求, /然后重定向到/results ,但我想直接重定向到/results

index.js:

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

results.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);

index.html格式:

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

我應該重定向到results.html進行渲染,但是我收到了Bad Request HTTP Bad Request代碼。 我的路線在src/routes/results.htmlsrc/views index.html位於src/public/pages/index.html

您應該使用body-parser ,因為默認情況下,express不知道如何處理json文件,而應該使用express.static來提供html文件。

我在這里將html文件夾的內容映射到localhost:5000 /。 因此,您可以在該文件夾中放置一個form.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");
}); 

然后在您的routes.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);

默認情況下,所有路由都訪問/路由。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM