如何在Ubuntu云服务器上安装MongoDB、Express、Angular和Node.js?

  • 发布时间:2022-01-23 16:57:36
  • 阅读次数:657

MEAN是一套开发前端和后端网站应用程序的JavaScript开源框架。该框架只需要用JavaScript一种语言,就可以编写网站前端和后端程序。MEAN代表MongoDB、Express、Anguar和Node.js。它们是互相独立的技术,但整合起来发挥更大的效用。首先我们要准备一台安装了Ubuntu 20.04操作系统的云服务器,并安装最新补丁。

安装MongoDB

执行以下命令安装MongoDB,并启动MongoDB。

$ sudo apt install -y mongodb
$ sudo systemctl start mongodb
$ sudo systemctl enable mongodb

安装Node.js及其依赖

使用NodeSource官方下载源,安装最新版本的Node.js

$ curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
$ sudo apt install -y nodejs gcc g++ make git

使用npm安装yarn和gulp。

$ sudo npm install -g yarn
$ sudo npm install -g gulp

克隆官方MeanJS代码库,并使用yarn安装依赖包。

$ git clone https://github.com/meanjs/mean
$ cd mean
$ yarn install

编写代码

编辑server.js文件。

$ nano server.js

添加如下代码到server.js文件中。

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();

app.use('/', (req, res) => {
    MongoClient.connect("mongodb://localhost:27017/test", function(err, db){
        db.collection('Example', function(err, collection){
            collection.insert({ pageHits: 'pageHits' });
            db.collection('Example').count(function(err, count){
                if(err) throw err;
                res.status(200).send('Page Hits: ' + Math.floor(count/2));
            });
        });
    });
});

app.listen(3000);
console.log('Server running at http://localhost:3000/');

module.exports = app;

测试

最后使用gulp工具编译。

$ gulp

为了验证服务器运行正常,数据库可以正常连接,我们访问:http://192.168.0.123:3000 ,如果出现"Page Hits:"的提示,说明MEAN平台已安装成功。其中192.168.0.123需要替换为实际IP。

【全文完】

< 上一篇:如何在Ubuntu云服务器上安装MongoDB、Express、React和Node.js? 下一篇:如何在Ubuntu云服务器上使用Apache创建网站? >