我试图让我的节点js返回并输出从HTML表单获取的值。
node.js文件如下
const app = express();
var path = require('path');
var fs = require('fs');
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/myform', function(req, res) {
var myText = req.query.mytext;
res.send('Your Text:' +myText);
fs.writeFile('app.py',myText,function(err) {
if(err) throw err;
});
});
app.listen(3000, () => console.log('listening on port 3000!'));
HTML是
<!DOCTYPE html>
<html>
<body>
<h1 style="color:Blue">Docker</h1>
<div id="floating-panel">
<form action="/myform" method="post">
<input type="text" name="mytext" required />
<input type ="submit" value="Submit">
</form>
</div>
</body>
</html>
当我填写表格时,得到输出“ Your Text:undefined”,为什么不更新myText变量?
答案 0 :(得分:0)
这是您需要做的: index.js
var express = require('express');
const app = express();
var path = require('path');
var fs = require('fs');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/myform', function(req, res) {
var myText = req.body.mytext;
res.send('Your Text:' +myText);
fs.writeFile('app.py',myText,function(err) {
if(err) throw err;
});
});
app.listen(3000, () => console.log('listening on port 3000!'));
答案 1 :(得分:0)
req.query.mytext错误。 req.query在您要提取查询字符串时使用。 我认为在这里您需要使用req。正文,请用以下代码替换您的代码
const app = express();
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.post('/myform', function(req, res) {
const myText = req.body.mytext;
res.send('Your Text:' +myText);
fs.writeFile('app.py',myText,function(err) {
if(err) throw err;
});
});
app.listen(3000, () => console.log('listening on port 3000!'));