[英]Securely passing variable from client side javascript to nodejs server
[英]How to accessing client side javascript variable from server side nodejs?
我想从服务器端访问客户端的变量“ content”,我该怎么做?
extends layout
block content
div(id="ineditortxt")
h1(name="headings") #{title}
a(href='/signout', class='text-center new-account') Sign Out
div(id="editor")
|public class #{title}{
| public static void main(String[] args) {
|
| }
|}
script(src="src/ace.js", type="text/javascript")
script(type="text/javascript").
var editor=ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/java");
function getText(){
event.preventDefault();
var content = editor.getValue();
return false;
}
form(name="Save", id = "save", onsubmit="getText()")
input(type="submit", value="Save")
这取决于您要为应用程序使用哪种协议。
如果您使用传统的http,并且在node中运行了Express(http)服务器,则应遵循本文中描述的内容 。 您的客户端正在向服务器发送http-post请求,这样您就可以从html表单访问变量。 在纯html中,表单看起来像这样:
<form action="/save" method="post">
<input id="save" type="text" />
<input type="submit" value="Save" />
</form>
您将使用express在服务器端捕获的URL是http://your-page.com/save
app.post('/save', function(req, res) { ...
您还可以使用“现代” WebSocket协议 ,客户端和服务器之间可以“更加自然地交流”,但是它又是新事物,并不总是很容易集成到现有的http-infrastructur中。 对于websocket,可以将模块: socket.io用于节点,也可以与Express HTTP服务器结合使用。
然后看起来像这样:
var express = require('express'),
app = express(),
server = require('http').Server(app),
// Implementation of the WebSocket protocol.
io = require('socket.io')(server);
server.listen(3000); // port your server is listening, test with localhost:3000
io.on('connection', function (socket) {
socket.on('save', function (content) {
// do something with your content variable
});
});
并在客户端(使用jquery):
var socket = io();
$('#save').click(function () {
socket.emit('save', content);
});
如果您决定使用websocket,建议您看一下这个简单的聊天实现 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.