我正在编写一个Web应用程序,允许我从控制面板控制lgWebOS智能电视。我有一个使用Node.js和Express设置的服务器,当请求'/'时,将返回一个带有输入区域的基本HTML文件来更改音量。我希望能够将文本/输入框中的数据发送回我的服务器以传递给lgTV。代码:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximux-scale=1, user-scalable=no">
<title>lgWebOS App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<style type="text/stylesheet">
h1{
font-family: fantasy;
color: black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var vol;
$('#volSubmit').on('click', function(){
vol = $("#volVal").val();
$.post("http://localhost:3000/volume",
{volVal: vol}, function(data){
if(data==='done'){
alert('Volume Changed');
}
});
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="container col-md-12">
<h1 id="title" style="text-align:center;">LGwebOS Application</h1>
</div>
<div class="volume col-md-6">
<h3>Set Volume Here</h3>
<input type="text" id="volVal" value="3">
<input type="button" id="volSubmit" value="Set">
</div>
</div>
</body>
</html>
服务器/ Node.js的:
module.exports = {
config: expressConfig,
getHome: getHome,
post: volPost,
start: runServer
}
var lgtv = require('./webOS.js')
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
function expressConfig(){
lgtv.config();
app.use(bodyParser.json());
app.use(function(req, res, next){
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
});
app.set('views', __dirname = './views');
app.set('views engine', 'ejs');
app.engine('html', require('ejs').renderFile);
}
function getHome(){
app.get('/', function(req, res){
res.render('index.html');
});
}
function volPost(){
app.post('/volume', function(req, res){
console.log(req.body);
var level = req.body.volVal;
console.log(level);
lgtv.setVol(level);
});
}
function runServer(){
var server = app.listen(3000, function(err){
if(err){
console.log('An error occred: ' + err);
}
console.log('Web server is running on localhost port 3000');
});
}
在服务器文件中,在我的volPost函数中,我将其设置为记录变量'level'和请求体。变量级别应该是从HTML发送的数据,但它返回为undefined,请求体返回为空的JS对象。