簡體   English   中英

從 html 表單中獲取用戶輸入並將其寫入文本、csv 或其他數據庫文件(express.js、node.js、html)

[英]Get user input from html form and write it to text, csv or other database file (express.js, node.js, html)

我有一個網站,用戶可以在其中請求他們想要查看文章的汽車。 我想將輸入保存到服務器端文件(未保存到用戶的計算機)中,以便我可以看到用戶想要閱讀的內容。

服務器代碼(express.js、node.js):

var express = require('express');
var app = express();

app.set('trust proxy', true)

//setting middleware
app.use(express.static('/', {index:"/seriousindex.html"})); //Serves resources from public folder
console.log(__dirname);

app.use(express.static(__dirname+"/resources/css"));
app.use(express.static(__dirname+"/resources/js"));
app.use(express.static(__dirname+"/resources/audio"));
app.use(express.static(__dirname+"/resources/visual"));

app.get('/', (req, res)=> {
    res.sendFile('/seriousindex.html', {root:__dirname});
});

app.get('/*', function (req, res) {
    console.log(req.originalUrl);
    console.log(req.ip.split(':').pop());
    res.sendFile(__dirname + req.originalUrl.replace("?", ""));
});

PORT = 9001
app.listen(PORT, () => {
 console.log(`Server is listening on port: ${PORT}`);
})

輸入表單(HTML):

<label>
    Enter a car you want to see info on here: 
    <form>
        <input type = "form" id = "requestinput" placeholder = "Write here"></input>
        <input type = "submit" method = "POST" onclick = "/submit"></input>
    </form>
</label>    

我更喜歡使用 node.js 或 HTML 而不是 php 的答案,但如果 php 腳本有效,我可能仍會使用它。 我從 StackOverflow 復制了很多代碼,所以我的代碼會出現不一致的情況。 幫助表示贊賞。

更新! 您必須添加一個名為 bodyParser 的附加模塊,它是一個幫助您解析傳入請求正文的中間件。 對不起,我才意識到!

...express()

var bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

app.post('/car', (req, res) => {
...

在輸入表單的元素中,您需要指定屬性“action”。 更新! 此外,您必須向字段添加“名稱”屬性,以便將數據標記為這樣的鍵,例如{“requestinput”:“honda”}

<label>
    Enter a car you want to see info on here: 
    <form action="/car" method="POST"> 
        <input type ="text" name="requestinput" placeholder="Write here"></input>
        <input type = "submit"></input>
    <!-- This onclick is used to call a function inside the <script> of the html. In your case, the html has no function inside <script></script> so it does nothing -->
    </form>
<label>

那么您的應用程序將需要有一條名為“/car”的路線來接收輸入

app.post('/car', (req, res)=>{
    console.log('Data', req.body.requestinput) // changed to body
    // save the data here
})

暫無
暫無

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

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