使用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其实都没学,搞的什么都要百度,耽误了非常多的时间,有空系统的学一下吧

发布了24 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Protocols7/article/details/90110390