node mongoose

by Arun Mathew Kurian

通过阿伦·马修·库里安(Arun Mathew Kurian)

如何使用Express,Mongoose和Socket.io在Node.js中构建实时聊天应用程序 (How to build a real time chat application in Node.js using Express, Mongoose and Socket.io)

In this tutorial, we will use the Node.js platform to build a real time chat application that sends and shows messages to a recipient instantly without any page refresh. We will use the JavaScript framework Express.js and the libraries Mongoose and Socket.io to achieve this.

在本教程中,我们将使用Node.js平台构建实时聊天应用程序 ,该应用程序可以立即发送和显示消息给收件人,而无需刷新页面。 我们将使用JavaScript框架Express.js以及库Mongoose和Socket.io实现此目的。

Before we start, lets have a quick look at the basics of Node.js

在开始之前,让我们快速看一下Node.js的基础知识

Node.js (Node.js)

Node.js is an open-source, cross-platform JavaScript run-time environment that executes JavaScript code outside the browser. The most important advantage of using Node is that we can use JavaScript as both a front-end and back-end language.

Node.js是一个开源,跨平台JavaScript运行时环境,可在浏览器外部执行JavaScript代码。 使用Node的最重要优势是我们可以将JavaScript既用作前端语言又用作后端语言。

As we know, JavaScript was used primarily for client-side scripting, in which scripts were embedded in a webpage’s HTML and run client-side by a JavaScript engine in the user’s web browser.

众所周知,JavaScript主要用于客户端脚本编写,其中脚本被嵌入到网页HTML中,并由用户Web浏览器中JavaScript引擎在客户端运行。

Node.js lets developers use JavaScript to write Command Line tools and for server-side scripting — running scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser.

Node.js允许开发人员使用JavaScript编写命令行工具和服务器端脚本-在页面发送到用户的Web浏览器之前在服务器端运行脚本以生成动态网页内容。

To install node:

要安装节点:

https://nodejs.org/en/download/

https://nodejs.org/en/download /

Even though the node is single threaded it’s still faster to use asynchronous functions. For example, Node can process other things while a file is being read off disk, or while waiting for an HTTP request to complete. The asynchronous behaviour can be implemented using callbacks. Also the JavaScript works well with JSON and No-SQL databases.

即使节点是单线程的,使用异步函数仍然更快。 例如,在从磁盘上读取文件时或在等待HTTP请求完成时,Node可以处理其他事情。 可以使用回调实现异步行为。 JavaScript也可以与JSON和No-SQL数据库一起很好地工作。

NPM模块 (NPM Modules)

Nodejs allows the modules of libraries to be included in the application. These modules can be user-defined or third party modules.

Nodejs允许将库模块包含在应用程序中。 这些模块可以是用户定义的模块或第三方模块。

The third party modules can be installed using the following command:

可以使用以下命令来安装第三方模块:

npm install module_name

and the installed modules can be used using the require() function:

并且可以使用require()函数使用已安装的模块:

var module = require(‘module_name’)

In Node apps we will be using a package.json file to maintain the module versions. This file can be created by this command:

在Node apps中,我们将使用package.json文件来维护模块版本。 可以通过以下命令创建此文件:

npm init

and the packages must be installed as follows:

并且必须按照以下步骤安装软件包:

npm install -s module_name

There are many frameworks that can be added as modules to our Node application. These will be explained further on as needed.

可以将许多框架作为模块添加到我们的Node应用程序中。 这些将根据需要进一步解释。

简单聊天应用 (Simple Chat Application)

The app must allow multiple users to chat together. The messages must be updated without refreshing the page. For simplicity we will be avoiding the authentication part.

该应用程序必须允许多个用户一起聊天。 消息必须更新而不刷新页面。 为简单起见,我们将避免身份验证部分。

We can start by creating a new project directory and moving into it. Then we can initiate our project by the following command:

我们可以先创建一个新的项目目录并移入其中。 然后我们可以通过以下命令启动我们的项目:

npm init

This will prompt us to enter details about our project.

这将提示我们输入有关我们项目的详细信息。

After this a package.json file will be created:

之后,将创建一个package.json文件:

{“name”: “test”,“version”: “1.0.0”,“description”: “”,“main”: “index.js”,“scripts”: {“test”: “echo \”Error: no test specified\” && exit 1"},“author”: “”,“license”: “ISC”
}

Our app directory is now set.

现在我们的应用程序目录已设置。

The first thing we need to create is a server. In order to create that, we will be making use of a framework named Express.

我们需要创建的第一件事是服务器。 为了创建它,我们将使用一个名为Express的框架

Express.js (Express.js)

Express.js, or simply Express, is a web application framework for Node.js. Express provides a robust set of features for web and mobile applications. Express provides a thin layer of fundamental web application features, without obscuring Node.js features.

Express.js,或简称为Express,是Node.js的Web应用程序框架。 Express 为Web和移动应用程序提供了一组强大的功能 。 Express提供了基本的Web应用程序功能薄层,而不会模糊Node.js功能。

We will install Express.js using the following command:

我们将使用以下命令安装Express.js:

npm install -s express

Inside the package.json file a new line will be added:

在package.json文件中,将添加新行:

dependencies”: {“express”: “⁴.16.3”}

Next we will create a server.js file.

接下来,我们将创建一个server.js文件。

In this file we need to require Express and create a reference to a variable from an instance of Express. Static contents like HTML, CSS or JavaScript can be served using express.js:

在此文件中,我们需要Express并从Express实例创建对变量的引用。 可以使用express.js来提供HTML,CSS或JavaScript之类的静态内容:

var express = require(‘express’);var app = express();

and we can start listening to a port using the code:

我们可以使用以下代码开始监听端口:

var server = app.listen(3000, () => {console.log(‘server is running on port’, server.address().port);
});

Now we need to create an HTML file index.html that displays our UI. I have added bootstrap and JQuery cdn.

现在,我们需要创建一个HTML文件index.html来显示我们的UI。 我添加了bootstrap和JQuery CDN。

//index.html<!DOCTYPE html>
<html>
<head><! — include bootstap and jquery cdn →
</head>
<body>
<div class=”container”><br><div class=”jumbotron”><h1 class=”display-4">Send Message</h1><br><input id = “name” class=”form-control” placeholder=”Name”><br><textarea id = “message” class=”form-control” placeholder=”Your Message Here”>
</textarea><br><button id=”send” class=”btn btn-success”>Send</button></div><div id=”messages”></div>
</div>
<script></script>
</body>
</html>

Please note that the empty <script> <;/script>tag will be the place where we will write the client side JavaScript code.

请注意,空的<script> < ; / script>标记将是我们编写客户端JavaScript代码的地方。

In-order to tell Express that, we will be using a static file. We will add a new line inside server.js:

为了告诉Express,我们将使用静态文件。 我们将在server.js中添加新行

app.use(express.static(__dirname));

We can run the server.js using the command

我们可以使用以下命令运行server.js

node ./server.js

or a package called nodemon, so that the changes made in the code will be automatically detected. We will download nodemon using the command

或称为nodemon的软件包,以便自动检测代码中所做的更改。 我们将使用以下命令下载nodemon

npm install -g nodemon

-g — global, so that it is accessible in all projects.

-g-全局,以便在所有项目中都可以访问。

We will run the code using the command

我们将使用以下命令运行代码

nodemon ./server.js

If you go to localhost:3000 we can see the index file:

如果您访问localhost:3000,我们可以看到索引文件:

Now that our server is up and running, we need to create our database. For this app we will having a No-SQL database and will be using Mongodb. I am setting up my mongodb in mlab.com. Our database will contain a single collection called messages with fields name and message.

现在我们的服务器已启动并正在运行,我们需要创建数据库。 对于此应用程序,我们将具有No-SQL数据库,并将使用Mongodb 。 我正在mlab.com中设置mongodb。 我们的数据库将包含一个名为messages的单个集合,其中包含namemessage字段

In-order to connect this database to the app, we will use another package called Mongoose.

为了将此数据库连接到应用程序,我们将使用另一个名为Mongoose的软件包。

猫鼬 (Mongoose)

Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. Mongoose can be installed using the command

Mongoose是设计用于异步环境的MongoDB对象建模工具。 可以使用以下命令安装猫鼬

npm install -s mongoose

Inside server.js we will require mongoose:

server.js内部,我们将需要猫鼬:

var mongoose = require(‘mongoose’);

And we will assign a variable, the URL of our mlab database:

我们将分配一个变量,即mlab数据库的URL:

var dbUrl = ‘mongodb://username:pass@ds257981.mlab.com:57981/simple-chat’

Mongoose will connect to the mlab database with the connect method:

猫鼬将使用connect方法连接到mlab数据库:

mongoose.connect(dbUrl , (err) => { console.log(‘mongodb connected’,err);
})

And we will be defining our message model as

我们将定义消息模型为

var Message = mongoose.model(‘Message’,{ name : String, message : String})

We can implement the chat logic now. But before that there is one more package that needs to be added.

我们现在可以实现聊天逻辑。 但是在此之前,还需要添加一个软件包。

身体解析器 (Body-Parser)

Body-Parser extracts the entire body portion of an incoming request stream and exposes it on req.body. The middleware was a part of Express.js earlier, but now you have to install it separately.

Body-Parser提取传入请求流的整个主体部分,并将其公开在req.body上。 中间件是Express.js的一部分,但现在您必须单独安装。

Install it using the following command:

使用以下命令安装它:

npm install -s body-parser

Add the following codes to server.js:

将以下代码添加到server.js:

var bodyParser = require(‘body-parser’)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))

路由 (Routing)

Routing refers to how an application’s endpoints (URIs) respond to client requests. You define routing using methods of the Express app object that correspond to HTTP methods: app.get() to handle GET requests and app.post() to handle POST requests.

路由是指应用程序的端点(URI)如何响应客户端请求。 您可以使用Express应用程序对象的与HTTP方法相对应的方法来定义路由:app.get()处理GET请求和app.post()处理POST请求。

These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified routes and methods, and when it detects a match, it calls the specified callback function.

这些路由方法指定在应用程序收到对指定路由(端点)和HTTP方法的请求时调用的回调函数 (有时称为“处理函数”)。 换句话说,应用程序“侦听”与指定的路由和方法匹配的请求,并且当它检测到匹配项时,它将调用指定的回调函数。

Now we need to create two routes to the messages for our chat to work.

现在,我们需要为消息创建两条路由,以便我们的聊天工作。

Inside server.js:

内部server.js:

get : will get all the message from database

get:将从数据库中获取所有消息

app.get('/messages', (req, res) => {Message.find({},(err, messages)=> {res.send(messages);})
})

post : will post new messages created by the user to the database

post:将用户创建的新消息发布到数据库中

app.post('/messages', (req, res) => {var message = new Message(req.body);message.save((err) =>{if(err)sendStatus(500);res.sendStatus(200);})
})

In order to connect these routes to the front end we need to add the following code in the client side script tag in the index.html:

为了将这些路由连接到前端,我们需要在index.html的客户端脚本标签中添加以下代码

$(() => {$("#send").click(()=>{sendMessage({name: $("#name").val(), message:$("#message").val()});})getMessages()})function addMessages(message){$(“#messages”).append(`<h4> ${message.name} </h4><p>  ${message.message} </p>`)}function getMessages(){$.get(‘http://localhost:3000/messages', (data) => {data.forEach(addMessages);})}function sendMessage(message){$.post(‘http://localhost:3000/messages', message)}

Here the sendMessage is used to invoke the post route of the messages, and save a message sent by the user. The message is created when a user clicks the send button.

在这里, sendMessage用于调用消息的发布路由,并保存用户发送的消息。 当用户单击发送按钮时,将创建该消息。

Similarly the getMessage is used to invoke the get route of messages. This will get all the messages saved in the database and will be appended to the messages div.

类似地, getMessage用于调用消息的get路由。 这将获取所有保存在数据库中的消息,并将被添加到消息div中。

The only issue now is that there is no way for the client to know if the server is updated. So each time we post a message we need to refresh the page to see the new messages.

现在唯一的问题是客户端无法知道服务器是否已更新。 因此,每次发布消息时,我们都需要刷新页面以查看新消息。

To solve this we can add a push notification system that will send messages from server to client. In Node.js we use socket.io.

为了解决这个问题,我们可以添加一个推送通知系统,该系统将从服务器向客户端发送消息。 在Node.js中,我们使用socket.io。

套接字 (Socket.io)

Socket.IO is a JavaScript library for realtime web applications. It enables realtime, bi-directional communication between web clients and server. It has two parts: a client-side library that runs in the browser, and a server-side library for Node.js. Socket.io enables real-time bidirectional event-based communication.

Socket.IO是一个用于实时Web应用程序JavaScript库。 它支持Web客户端和服务器之间的实时双向通信 。 它包含两个部分:在浏览器中运行的客户端库和用于Node.js的服务器端库。 Socket.io支持基于事件的实时双向通信。

To install socket.io:

要安装socket.io:

npm install -s socket.io

we also need an HTTP package for Socket.io to work:

我们还需要一个HTTP包才能使Socket.io正常工作:

npm install -s http

Add the following code to server.js:

将以下代码添加到server.js:

var http = require(‘http’).Server(app);
var io = require(‘socket.io’)(http);

And we can create a connection:

我们可以创建一个连接:

io.on(‘connection’, () =>{console.log(‘a user is connected’)
})

In the index.html add the following tag:

index.html中添加以下标记:

<script src=”/socket.io/socket.io.js”></script>

Now we need to create an emit action when a message is created in server.js. So the post route becomes this:

现在,当在server.js中创建消息时,我们需要创建一个发射动作。 因此发布路线变为:

app.post('/messages', (req, res) => {var message = new Message(req.body);message.save((err) =>{if(err)sendStatus(500);io.emit('message', req.body);res.sendStatus(200);})
})

And in the client side script tag in index.html, add the following code:

然后在index.html的客户端脚本标记中添加以下代码:

var socket = io();socket.on(‘message’, addMessages)

So each time a message is posted, the server will update the messages in the message div.

因此,每次发布消息时,服务器都会在消息div中更新消息。

Great!!

大!!

This is very basic application that we can create in Node.js. There is lot of scope for improvement. The finished code can be found in https://github.com/amkurian/simple-chat

这是我们可以在Node.js中创建的非常基本的应用程序。 有很多改进的余地。 可以在https://github.com/amkurian/simple-chat中找到完成的代码

server.js

server.js

var express = require('express');
var bodyParser = require('body-parser')
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoose = require('mongoose');app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))var Message = mongoose.model('Message',{name : String,message : String
})var dbUrl = 'mongodb://username:password@ds257981.mlab.com:57981/simple-chat'app.get('/messages', (req, res) => {Message.find({},(err, messages)=> {res.send(messages);})
})app.get('/messages', (req, res) => {Message.find({},(err, messages)=> {res.send(messages);})
})app.post('/messages', (req, res) => {var message = new Message(req.body);message.save((err) =>{if(err)sendStatus(500);io.emit('message', req.body);res.sendStatus(200);})
})io.on('connection', () =>{console.log('a user is connected')
})mongoose.connect(dbUrl ,{useMongoClient : true} ,(err) => {console.log('mongodb connected',err);
})var server = http.listen(3001, () => {console.log('server is running on port', server.address().port);
});

Hope this was helpful in understanding some basic concepts.

希望这有助于理解一些基本概念。

Some useful links

一些有用的链接

Socket.IOSOCKET.IO 2.0 IS HERE FEATURING THE FASTEST AND MOST RELIABLE REAL-TIME ENGINE ~/Projects/tweets/index.js var io =…socket.ioExpress - Node.js web application frameworkExpress is a minimal and flexible Node.js web application framework that provides a robust set of features for web and…expressjs.com

Socket.IO SOCKET.IO 2.0拥有最快速,最可靠的实时引擎〜/ Projects / tweets / index.js var io =… socket.io Express-Node.js Web应用程序框架 Express是一个最小且灵活的节点.js Web应用程序框架,为Web和… Expressjs.com 提供了一组强大的功能

http://mongoosejs.com/

http://mongoosejs.com/

翻译自: https://www.freecodecamp.org/news/simple-chat-application-in-node-js-using-express-mongoose-and-socket-io-ee62d94f5804/

node mongoose

node mongoose_如何使用Express,Mongoose和Socket.io在Node.js中构建实时聊天应用程序相关推荐

  1. 视频教程-Node.JS - socket.io教程-Node.js

    Node.JS - socket.io教程 全栈开发工程师,现职于北京一家学院的全栈教学主任. 8年前端开发经验.4年移动端开发经验.4年UI设计经验.3年一线教学经验. 精通Node.JS.PHP. ...

  2. Day 27: Restify —— 在Node.js中构建正确的REST Web服务

    今天决定学一个叫做restify的Node.js模块.restify模块使得在Node.js中写正确的REST API变得容易了很多,而且它还提供了即装即用的支持,如版本控制.错误处理.CORS和内容 ...

  3. aws lambda_我如何在一天内在Node.js中构建无服务器的AWS Lambda Twitter机器人

    aws lambda Have you ever wanted to create a Twitter Bot? It's been on my list of things to do for qu ...

  4. 连接Python 3和Electron/Node.JS:构建现代桌面应用程序

    目录 先决条件 第1步--设置开发环境 安装Node.js和NPM 设置Python虚拟环境 创建虚拟环境 第4步--创建Node.js应用程序 如何在Electron和Python之间进行通讯 什么 ...

  5. 使用express、react、webpack打包、socket.io、mongodb、ant.design、less、es6实现聊天室

    拿到一个项目,我们应该如何去完成这个项目呢. 是直接上手? 还是先进行分析,然后再去解决呢?毫无疑问,如果直接上手解决,那么可能会因为知道目标所在,而导致出现各种问题. 所以,我们应该系统的分析这个项 ...

  6. 数据库、MongoDB/Mongoose、cookie与session、密码加密、图片处理、web Socket和Socket.IO框架

    一.传统数据库 数据库就是存储数据的,那么存储数据就用txt就行了啊,为什么要有数据库? 理由1: 数据库有行.列的概念,数据有关系,数据不是散的. 老牌数据库,比如MySQL.SQL Server. ...

  7. 使用Node.js+Socket.IO搭建WebSocket实时应用

    Web领域的实时推送技术,也被称作Realtime技术.这种技术要达到的目的是让用户不需要刷新浏览器就可以获得实时更新.它有着广泛的应用场景,比如在线聊天室.在线客服系统.评论系统.WebIM等. 作 ...

  8. Express+Socket.IO 实现简易聊天室

    代码地址如下: http://www.demodashi.com/demo/12477.html 闲暇之余研究了一下 Socket.io,搭建了一个简易版的聊天室,如有不对之处还望指正,先上效果图: ...

  9. express+socket.io 共享session

    express下socket.io使用session验证用户 作者: littlejim 时间: April 23, 2015 分类: node.js express下使用socket.io来传输用户 ...

最新文章

  1. 16、IN和NOT IN用法详解
  2. python医疗系统代码_吴裕雄 人工智能 java、javascript、HTML5、python、oracle ——智能医疗系统WEB端复诊代码简洁版实现...
  3. Spring 的优点
  4. ubuntu下安装jdk1.6.0_41
  5. Redis核心配置_Redis高级数据类型使用
  6. android 技能标签功能_android专业技能总结.doc
  7. Spark: history Server
  8. Linux下查看某个进程占用的CPU及内存
  9. 软件测试 第三次作业
  10. 数模美赛准备——我的第一个LaTex文档
  11. 使用docker安装部署postgres(带有postGis插件的)
  12. 护照、身份证识别阅读器
  13. Python生成随机数字/字符
  14. springboot微信点餐系统项目设计
  15. 【压力测试 2】JMeter压力测试之Internal server error 500 问题解决思路
  16. Echarts 坐标轴刻度间隔/全部显示
  17. socket技术路线_呐,这不就是你要的C++后台开发学习路线吗?
  18. android 手电筒闪烁,如何实现Android Studio简易手电筒的闪烁和报警功能
  19. RISC和CISC,究竟有何不同?
  20. java经典问题:一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下,求它在 第10次落地时,共经过多少米?第10次反弹多高?

热门文章

  1. php webapi验签,Asp.netCore3.0 WebApi从0到1手摸手教你写【5】增加接口参数签名验证...
  2. VUE还没生效,页面闪屏的问题解决办法 v-cloak
  3. iOS 走近商城 APP(三 WKWebView 商品规格选择框架封装)
  4. docker制作镜像篇(基于容器)
  5. tf.nn.relu
  6. SQLite与pandas
  7. 小型网站到大型网站-Mysql优化
  8. 使用HTML5监測站点性能
  9. MySQL(三)用正则表达式搜索
  10. vector、map删除当前记录