如何在Node.js中使用Express处理POST请求?我写了下面的代码不起作用

时间:2019-05-14 01:53:02

标签: node.js express

无法使用Node.js中的express处理后期请求数据。我想处理来自test.js文件中index.html文件的表单数据。出现错误: POST / test”错误(404):“未找到”

以下是我编写的代码:

index.html

<html>
    <body>
            <form action="/test" method="POST">
                Name: <input type="text" name="name"/>
                <input type="submit" value="Submit"/>
                </form>
    </body>
</html>

test.js

var express = require("express");
var bodyParser = require('body-parser');
var app = express();
var urlEncodedParser = app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: false
}));
app.post('/test',urlEncodedParser, function(req,res){
console.log("Kushagra "+req.body);
});
app.listen(8080,function(){
  console.log("Started in port 8080");
});

要完成从index.html文件到test.js文件的表单数据接收的操作。

1 个答案:

答案 0 :(得分:1)

// TODO: Place this code before route & put index.html to public directory

const path = require("path");

app.use(express.static(path.join(__dirname, "public")));