简体   繁体   English

如何在 Node.JS 上与浏览器交互

[英]How to interact with the browser on Node.JS

I am learning Node.Js, I would like to understand how to interact between front-end / backend.我正在学习 Node.Js,我想了解如何在前端/后端之间进行交互。

I would do backend --> Front End interaction by sendig data using app.get(), but now, I'd like to understand how can I get variable from Front End to Backend.我会使用 app.get() 通过发送数据进行后端 -> 前端交互,但是现在,我想了解如何从前端获取变量到后端。

Front-ENd.前端。 (I want to pass varGetFromFrontend to backend) (我想将 varGetFromFrontend 传递给后端)

<html>
<script>
var varGetFromFrontend = 2; // This is variable I want to pass to backend
</script>
<head>
    <title>Home Page</title>
</head>

<body>
<h1> This is a test</h1>


</body>
</html>

On Node.Js (backend)在 Node.Js 上(后端)

var express = require('express');
var app = new express();
app.use(express.json());
app.use(express.static(__dirname + '/public'));
     var entries = [
        {"id":1, "title":"Hello World!"},
        {"id":2, "title":"Hello World!"}
        {"id":3, "title":"Hello World!"}
        {"id":4, "title":"Hello World!"}
        ];
if(entries.id == varGetFromFrontend){
console.log("This is to print a variable by choosing it from Front End")
 console.log(varGetFromFrontend)
}

var port = Number(process.env.PORT || 5000);
app.listen(port);

I would like to know how can I print "varGetFromFrontend" on server side我想知道如何在服务器端打印“varGetFromFrontend”

Make an HTTP request to the server.向服务器发出 HTTP 请求。 Include the variable in the request.在请求中包含变量。

There are lots of ways to do this:有很多方法可以做到这一点:

Put it in a hidden input in a form, then submit the form.将其放入表单中的隐藏输入中,然后提交表单。

or要么

Set location.href to a new value and include the variable in it (eg in a query string)location.href设置为新值并在其中包含变量(例如在查询字符串中)

or要么

Use the XMLHttpRequest object to make an HTTP request使用XMLHttpRequest对象发出 HTTP 请求

or要么

Create a script element and include the variable in the URL for the src attribute创建一个script元素并在src属性的 URL 中包含该变量

(This is a non-exhaustive list) (这是一份非详尽清单)

You can interact with the nodejs server from the browser with socket.io您可以使用socket.io从浏览器与 nodejs 服务器交互

First, install socket.io:首先,安装socket.io:

npm install socket.io

and write these code to their respective filenames.并将这些代码写入各自的文件名。

app.js:应用程序.js:

var express = require("express");
var http = require("http");
var socketIO = require("socket.io");

var app = express();
app.get("/", function(req, res){
    res.sendfile("./index.html");
});

var server = http.createServer(app);
var io = socketIO.listen(server, {log: false});
io.sockets.on("connection", function(socket){
    socket.on("sendVar", function(value){
        console.log("The value of the variable is " + value);
    });
});

server.listen(5000);

index.html:索引.html:

<html>
    <head>
        <title>Index Page</title>
    </head>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>
    <script type="text/javascript">
        var variableFromFrontEnd = 2;
        var socket = io.connect("/");
        socket.on("connect", function(){
            console.log("connected!")
            socket.emit("sendVar", variableFromFrontEnd);
        });
    </script>
</html>

and run it.并运行它。

Check out the MEAN framework I built: http://mean.wolframcreative.com/查看我构建的 MEAN 框架: http : //mean.wolframcreative.com/

This uses Node as the back-end server utilizing Express as the API router.这使用 Node 作为后端服务器,使用 Express 作为 API 路由器。 The front-end uses angular and is purely an api consumption tool.前端使用angular,纯粹是一个api消费工具。

Short answer is this:简短的回答是这样的:

in angular:角度:

$http
    .get('/api/users/bobsaget')
    .success(function (response) {
        console.log(response);
    });

in node(with express):在节点(带快递):

app.get('/api/users/:username', function (req, res) {
    var variable = req.params.username;
    //do logic here with the database(mongo) to get user info:
    db.users.findOne({username: username}, function (error, response) {
        if (!error) {
            res.send(200, response);
        } else {
            res.send(500, {success: false, message: error.message});
        }
    });
)};

Long answer is to play around with my framework and get your hands dirty.长答案是玩弄我的框架并弄脏你的手。

I'm currently working on a restful framework for node call snooze.我目前正在研究一个用于节点调用贪睡的宁静框架。 I'm writing an api along side it and it's going very well.我正在编写一个 api,并且进展顺利。 The framework is written to be modular and easy to use.该框架被编写为模块化且易于使用。 Everything is built around modules, routes, controllers, services, and validators.一切都是围绕模块、路由、控制器、服务和验证器构建的。

https://github.com/iamchairs/snooze https://github.com/iamchairs/snooze

snooze.module('myServer', ['snooze-stdlib']) // inject the snooze-stdlib module
    .route('get', '/users/:username', { // define the route
        controller: 'UserCtrl', // what controller should handle this route
        action: 'getUserByUsername', // what action to perform on this route
        validator: 'GetUsername' // before processing this action what validation should occur
    })
    .controller('UserCtrl', function(User) { // inject the User service
        return {
            getUserByUsername: function(res, options) {
                User.getUserByUsername(options.query.username).then(function(username) {
                    res.send(200, username);
                }).fail(function(err) {
                    res.send(500, err);
                });
            }
        };
    })
    .service('User', function($q) { // inject the $q service
        return {
            getUserByUsername: function() {
                var deferred = $q.defer();

                deferred.resolve('iamchairs');

                return deferred.promise;
            }
        };
    })
    .validator('GetUsername', function($validator) { // inject the validator service
        return function(deferred, req) {
            if($validator.isLength(req.query.username, 2, 32)) {
                deferred.resolve(); // resolve (valid request)
            } else {
                deferred.reject([400, 'Username must be between 2 and 32 characters']); // reject (invalid request)
            }
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM