【Node.js】使用express搭建web服務器實現文本傳輸

起因

想把手機(ios)中的部分文本傳輸給電腦(win),又不想登陸社交軟件,想找一個跨越操作系統的文本傳輸方法。如果手機和電腦在同一局域網中,根據計算機網絡的知識大概有如下幾種方法:

  • 使用tcp協議:創建兩個套接字,使用C語言原生套接字api接收發送信息(手機如何運行C程序?)
  • 使用http協議:在電腦上搭建web服務器,寫帶文本框的頁面,手機打開並用post方法提交文本,電腦這邊console.log輸出或用js展現在頁面上

開幹

express

express是node.js中的web框架。於是用express快速搭建了一個web服務器:

var express =require('express')
var bodyParser = require('body-parser')
var app = express()

//配置body-parser中間件 解析post請求體
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

//配置模板引擎
app.engine('html',require('express-art-template'))

app.get('/index/',function(req,res){
    res.render('index.html')
})
app.post('/index/',function(req,res){
    console.log(req.body)
})

app.listen(80,function(){
    console.log('running')

})

html

然後寫首頁,肯定是要post方法提交表單,於是在bootstrap官網找了個模板。由於不懂如何提交表單,百度了一波寫出了這個:

    <form action="/index" method="POST">
        <input type="text" name="text" >
        <button type="submit" class="btn btn-default">Submit</button>
    </form>

效果爲:

<form action="/index" method="POST">
    <input type="text" name="text"  id="">
    <button type="submit" class="btn btn-default">Submit</button>
</form>

但是感覺輸入框太小了。使用style="width:200px;height:100px"可以改變文本框大小,但是文字居中了不能換行,查了一會發現input就是爲了單行輸入的,如果要多行輸入可以用textarea。於是改成這樣:

    <form action="/index" method="POST">
        <textarea name="text" cols="30" rows="10"></textarea><br>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>

在服務器端通過req.body就可以拿到文本了,這時候直接從控制檯複製,就可以拿到 我買的XX激活碼 文本了。

app.post('/index/',function(req,res){
    console.log(req.body.text)
})

如下:
點擊提交,在控制檯得到文本

jQuery

還有別的方法嗎?正好最近學了vue.js,想到獲取textarea中的數值,寫到data,用它的data屬性給實時展現在界面上,但是vue好像不提倡直接操作dom,所以用jquery試試:

<div >
    <textarea id="text"  cols="30" rows="10"></textarea><br>
    <button type="button" id="button">顯示文本</button><br>
    <textarea id="text2"  cols="30" rows="10"></textarea><br>
</div>

<script>
    var t=null
    $('#button').click(function () {
        t=$('#text').val()
        console.log(t);
        $('#text2').append(t)
    })
</script>

最後發現不對勁,如果手機端不把數據post或者get給服務器端,單純在自己的文本框內修改,電腦端是無法獲得文本的。。。所以這種方法不行。。

總結

html、js其實都沒學,搞的什麼都要百度,耽誤了非常多的時間,有空系統的學一下吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章