我很難從 HTML 表單中檢索快速發布請求的正文。在我的代碼中,我嘗試使用 JSON.stringify 提取它通常是原始的。仍然沒有骰子,只是輸出:""Body: "undefined" 在 app.js 中收到!------- Body: "[object Object]" received in app.js!"" 控制臺輸出 undefined 和 {}。任何幫助表示贊賞。Bellow 是我的 JS 代碼和 HTML 代碼。
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(express.urlencoded({
extended: true
}))
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, './index.html'));
})
app.post('/submit-form', function(req, res) {
var x = req.body.key;
var y = req.body;
console.log(x);
console.log(y);
console.log(JSON.stringify(x));
console.log(JSON.stringify(y));
res.send(`Body: "${x}" recieved in app.js! ------- Body: "${y}" recieved in app.js!`);
})
app.listen(4001, function() {
console.log("Server is listening on port 4001...");
})
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Site</title>
<style>
body { padding-top: 50px; }
</style>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>res.sendFile() Works!</h1>
<form method="POST" action="/submit-form", body= "key: 'hellow wolrd'"}>
<input type="submit">
</form>
</div>
</div>
</body>
</html>```
uj5u.com熱心網友回復:
POST請求的主體是由命名為表單控制元件(的值確定input,select在形式等元素)。
元素沒有body屬性<form>。
MDN 有一個 forms express 教程,我推薦你閱讀。
<form method="POST" action="/submit-form">
<input name=key value="hello, world">
<button>Submit</button>
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381615.html
標籤:javascript html 节点.js 邮政
