Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.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
为什么将JSON参数从HTML传递到Node.js会导致body参数未定义_Node.js_Json_Html Post - Fatal编程技术网

为什么将JSON参数从HTML传递到Node.js会导致body参数未定义

为什么将JSON参数从HTML传递到Node.js会导致body参数未定义,node.js,json,html-post,Node.js,Json,Html Post,我第一次尝试使用Node.js将参数从表单传递到服务器,并在控制台上打印它们 我的html <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Hello Node</title>

我第一次尝试使用Node.js将参数从表单传递到服务器,并在控制台上打印它们

我的html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Hello Node</title>
    </head>

    <body>

    <h1> we have a website</h1>
    <form action="/contact" enctype="application/json" method="POST">
        <input name="firstName" placeholder="firstName" type="text" size="30" />
        <input name="lastName" placeholder="lastName" type="text" size="30" />
    
        <input name="submit" type="submit" value="Send This">
    </form>

    </body>
</html>
  • 我试过使用和不使用app.use(bodyParser.json({type:'application/*+json'}))
输出:

[对象]

请求主体名称:未定义

请求查询名字:根据
application/json未定义的内容类型不允许设置为enctype值,因此您可以使用javascript发送json,或者通过
app.use(bodyParser.urlencoded({extended:false})添加对application/x-www-form-urlencoded的支持

bodyParser.urlencoded——我认为在URL字符串中传递参数时需要使用它,即:/contact/?firstname:“kukula”
const express = require('express'); 
const app = express();
const bodyParser = require('body-parser') 
var jsonParser = bodyParser.json()

app.listen(3333, () => {
    console.log("Server is up and listening on 3003"); //print to the server console (the terminal!!)
})

app.post("/contact", jsonParser, function (req, res) {
  console.log("in /contact");
  console.log("request body:" + req.body);
  console.log("request body first name:" + req.body.firstName);
  console.log("request query first name:" + req.query.firstName);
})