簡體   English   中英

未定義的節點js返回值

[英]undefined node js return value

我試圖讓我的節點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變量?

這是您需要做的: 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!'));

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!'));

暫無
暫無

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

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