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

青春壹個敷衍的年華 提交于 2020-01-13 10:33:34

问题


I have seen other questions with the same error, but none of the answers seem to work.

<!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.");
    }
};

Each time, when I submit the form, it shows

Cannot POST /del


回答1:


In your server.js change this line:

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

to this:

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

then you have correct router.

And your del.js change to this:

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

because router function should return response.



来源:https://stackoverflow.com/questions/34574522/shows-error-cannot-post-when-i-try-to-submit-the-html-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!