Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 请求post后的Req.body={}_Javascript_Html_Node.js_Express_Post - Fatal编程技术网

Javascript 请求post后的Req.body={}

Javascript 请求post后的Req.body={},javascript,html,node.js,express,post,Javascript,Html,Node.js,Express,Post,我有以下代码: app.use(express.static(__dirname)); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // support json encoded bodies app.get('/', function(req, res){ res.sendFile(__dirname+'index.html') }); app.get('/ins.html

我有以下代码:

app.use(express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // support json encoded bodies

app.get('/', function(req, res){
res.sendFile(__dirname+'index.html')
});

app.get('/ins.html', function(req, res){
res.sendFile(__dirname+'ins.html')
});

app.post('/ins', function(req, res){
console.log(req.body)
res.redirect('/')
});
代码如下:

<form method="post" enctype="multipart/form-data" action="/ins"><p>  <strong>INSERISCI LA TUA CAGATA<br></strong>
                            <br><p>Username&nbsp</p> <input type="text" name="username" required><br>
                            <br><p>Password &nbsp</p> <input type="password" name="password" required><br><br><br>
                        <input type="submit" class="mainBtn" id="submit" value="Inserisci Cagata">
                        <p>
                    </form></h2>
卡加塔酒店

用户名



密码
当我转到页面时,在che控制台中显示“{}”,并且我没有访问POST变量。
如何解决此问题?

您使用的编码与身体分析器支持的编码不同

您正在表单中使用多部分编码(
multipart/form data
),但服务器需要JSON(
application/JSON
)或URL编码数据(
application/x-www-form-urlencoded

除非需要上载文件(需要多部分编码),否则应使用URL编码(如果未指定
enctype
,则使用URL编码)。然后使用
bodyParser.urlencoded()解析器正确解析主体:

<form method="post" enctype="application/x-www-form-urlencoded" action="/ins">
                      <!--   ^--- note the enctype   -->
  <p>
    <strong>INSERISCI LA TUA CAGATA<br></strong>
    <br>
    <p>Username&nbsp</p>
    <input type="text" name="username" required>
    <br>
    <br>
    <p>Password &nbsp</p>
    <input type="password" name="password" required>
    <br>
    <br>
    <br>
    <input type="submit" class="mainBtn" id="submit" value="Inserisci Cagata">
  </p>
</form>


卡加塔酒店

用户名



密码





如果您确实需要多部分编码(例如,如果您正在上载文件),则可以使用多部分正文解析器(例如或)。请注意,因为多部分编码是一种复杂的编码,所以您不会直接获得
req.body
,但您必须自己进行一些解析,这就是为什么您应该避免多部分编码,除非您确实需要它