簡體   English   中英

為什么將 JSON 參數從 HTML 傳遞到 Node.js 導致 body 參數未定義

[英]Why passing JSON parameters from HTML to Node.js results in body parameter is undefined

我第一次使用 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>
  • 我試過有和沒有enctype="application/json"

我的 app.js 文件

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);
})
  • 我試過有和沒有app.use(bodyParser.json({ type: 'application/*+json' }))

輸出:

[對象對象]

請求正文名字:未定義

請求查詢名字:未定義

根據Mozilla 文檔application/json內容類型不允許設置為 enctype 值,因此您可以使用 javascript 發送 json 或通過app.use(bodyParser.urlencoded({ extended: false }))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM