当我尝试提交 HTML 表单时显示错误 "Cannot POST"

Shows error "Cannot POST" when I try to submit the HTML form

我看到其他问题有同样的错误,但 none 的答案似乎有效。

<!DOCTYPE html>
<html>
<body>

<form action="http://127.0.0.1:8080/del" method="post">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>

<p>Click on the submit button, and the input will be sent to a page on the server called "http://127.0.0.1:8080/del".</p>

</body>
</html>

server.js

var express=require('express');
var body_parser=require('body-parser');
var request = require('request').defaults({json:true});
var app=express();
var del=require('./del'); 
app.post('./del',del.test);
var server = app.listen(8080,function(){
    var host="127.0.0.1";
    var port="8080";
    console.log("App is listening at http://%s:%s\n",host,port);
});

del.js

module.exports={
    test: function(){
        console.log("Hello world.");
    }
};

每次提交表单时,它都会显示

Cannot POST /del

在您的 server.js 中更改此行:

app.post('./del',del.test);

对此:

app.post('/del',del.test);

那么你的路由器是正确的。

你的del.js改为:

module.exports={
    test: function(req, res){
        console.log("Hello world.");
        res.status(200).end();
    }
};

因为路由函数应该return响应。