【Nodejs&&ExpressJS&&AngularJS】安装与框架搭建

1.NodeJS

下载安装包

https://nodejs.org/download/

安装安装包

tar --strip-components 1 -xzvf node-v0.12.1-linux-x64.tar.gz -C /opt/app/nodejs_12

2.安装开发包

npm install -g express
npm install -g express-generator
npm install -g yo
npm install -g generator-angular
npm install -g bower
npm install -g nodemon

3.建立Front项目

cd $PROJECT_HOME
mkdir client
cd client
yo angular
vi client/Gruntfile.js
修改dist: ‘dist‘with dist: ‘../server/dist‘.
grunt serve
 
 
 http://localhost:9000测试前端静态页面

4。建立Backend

cd $PROJECT_HOME
mkdir server
express
npm install
mkdir dist
delete public views 文件夹
vi app.js 
 注释掉如下行:
app.set(‘views‘, path.join(__dirname, ‘views‘));
app.set(‘view engine‘, ‘jade’);
app.use(express.static(path.join(__dirname, ‘public‘)));
app.use(‘/‘, routes);
app.use(‘/users‘, users);

添加如下行

/**
 * Development Settings
 */
if (app.get(‘env‘) === ‘development‘) {
    // This will change in production since we‘ll be using the dist folder
    app.use(express.static(path.join(__dirname, ‘../client‘)));
    // This covers serving up the index page
    app.use(express.static(path.join(__dirname, ‘../client/.tmp‘)));
    app.use(express.static(path.join(__dirname, ‘../client/app‘)));

    // Error Handling
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render(‘error‘, {
            message: err.message,
            error: err
        });
    });
}

/**
 * Production Settings
 */
if (app.get(‘env‘) === ‘production‘) {

    // changes it to use the optimized version for production
    app.use(express.static(path.join(__dirname, ‘/dist‘)));

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render(‘error‘, {
            message: err.message,
            error: {}
        });
    });
}

vi server/package.json

"start": " nodemon ./bin/www",
"test": " nodemon ./bin/www"

npm uninstall jade --save

5.Connecting AngularJS with Express

cd client

1.add views/signup.html

2.modify app.js

‘use strict‘;

/**
 * @ngdoc overview
 * @name clientApp
 * @description
 * # clientApp
 *
 * Main module of the application.
 */
angular
  .module(‘clientApp‘, [
    ‘ngAnimate‘,
    ‘ngCookies‘,
    ‘ngResource‘,
    ‘ngRoute‘,
    ‘ngSanitize‘,
    ‘ngTouch‘
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when(‘/‘, {
        templateUrl: ‘views/main.html‘,
        controller: ‘MainCtrl‘
      })
      .when(‘/about‘, {
        templateUrl: ‘views/about.html‘,
        controller: ‘AboutCtrl‘
      })
      .when(‘/signup‘, {
        templateUrl: ‘views/signup.html‘,
        controller: ‘SignupCtrl‘
      })
        .otherwise({
        redirectTo: ‘/‘
      });
  });

3.添加scripts/signup.js

‘use strict‘;

angular.module(‘clientApp‘) // make sure this is set to whatever it is in your client/scripts/app.js
  .controller(‘SignupCtrl‘, function ($scope, $http) { // note the added $http depedency

    // Here we‘re creating some local references
    // so that we don‘t have to type $scope every
    // damn time
    var user,
      signup;

    // Here we‘re creating a scope for our Signup page.
    // This will hold our data and methods for this page.
    $scope.signup = signup = {};

    // In our signup.html, we‘ll be using the ng-model
    // attribute to populate this object.
    signup.user = user = {};

    // This is our method that will post to our server.
    signup.submit = function () {

      // make sure all fields are filled out...
      // aren‘t you glad you‘re not typing out
      // $scope.signup.user.firstname everytime now??
      if (
        !user.firstname ||
        !user.lastname ||
        !user.email ||
        !user.password1 ||
        !user.password2
      ) {
        alert(‘Please fill out all form fields.‘);
        return false;
      }

      // make sure the passwords match match
      if (user.password1 !== user.password2) {
        alert(‘Your passwords must match.‘);
        return false;
      }

      // Just so we can confirm that the bindings are working
      console.log(user);

      // Make the request to the server ... which doesn‘t exist just yet
      var request = $http.post(‘/signup‘, user);

      // we‘ll come back to here and fill in more when ready
      request.success(function (data) {
        // to be filled in on success
        console.log(data);
      });

      request.error(function (data) {
        // to be filled in on error
        console.log(data);
      });

    };

  });

4..modify Backend server

A.cd server

B.server/routes/signup.js

C.modify server/app.js

  在var app = express();前面添加

/** * Route Imports */var signup = require(‘./routes/signup‘);

在module.exports = app;后面添加

/**
 * Routes
 */
app.use(‘/signup‘, signup);

D.modify server/routes/signup.js

// Include Express
var express = require(‘express‘);
// Initialize the Router
var router = express.Router();

// Setup the Route
router.post(‘/‘, function (req, res) {

    // show the request body in the command line
    console.log(req.body);

    // return a json response to angular
    res.json({
        ‘msg‘: ‘success!‘
    });
});

// Expose the module
module.exports = router;

E:在控制台执行(windows)

cd server

Set NODE_ENV=development

npm test

http://localhost:3000/#/signup

6.Connecting Express with MongoDB

6.1 Install mongoose

http://mongoosejs.com/

$ npm install mongoose

6.2cd $PROJECT_HOME/server

a.mkdir database && mkdir database/schemas

b.cd database

c.create db.js

var mongoose = require(‘mongoose‘);
var config = require(‘../config/config.index‘);
var UserModel = require(‘./schemas/User‘);

var uri = ‘mongodb://‘ + config.mongo.uri + ‘/‘ + config.mongo.db;
var options = {
    server: {poolSize: 5}
};
mongoose.connect(uri, options);

// get an instance of our connection to our database
var db = mongoose.connection;

// Logs that the connection has successfully been opened
db.on(‘error‘, console.error.bind(console, ‘connection error:‘));
// Open the connection
db.once(‘open‘, function callback () {
    console.log(‘Databsae Connection Successfully Opened at ‘ + uri);
});

exports.user= UserModel;

d.cd database/schemas

e.create user.js

/**
 * Our Schema for Users
 */
var mongoose = require(‘mongoose‘);
//var bcrypt = require(‘bcrypt‘);
var Schema = mongoose.Schema;

// Define the User Schema
var userSchema = new Schema({
    firstname: { type: String, required: true },
    lastname: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    profile: {} // for extra information you may / may not want
});

// A method that‘s called every time a user document is saved..
userSchema.pre(‘save‘, function (next) {

    var user = this;
   next();
  /*  // If the password hasn‘t been modified, move along...
    if (!user.isModified(‘password‘)) {
        return next();
    }*/

  /*  // generate salt
    bcrypt.genSalt(10, function(err, salt){

        if (err) {
            return next(err);
        }

        // create the hash and store it
        bcrypt.hash(user.password, salt, function(err, hash){
            if (err) {
                return next(err);
            }
            user.password = hash;
            next();
        });
    });*/
});

// Password verification helper
userSchema.methods.comparePassword = function (triedPassword, cb) {
    /*bcrypt.compare(triedPassword, this.password, function(err, isMatch) {
        if(err) return cb(err);
        cb(null, isMatch);
    });*/
};

// The primary user model
var User = mongoose.model(‘User‘, userSchema);

module.exports = User;

f.modify router/signup.js

/**
 * This handles the signing up of users
 */
var express = require(‘express‘);
var router = express.Router();
var moment = require(‘moment‘);
var _ = require(‘underscore‘);
var color = require(‘cli-color‘);
var db = require(‘../database/db‘);
var User = db.user;

// The POST /signup route
router.post(‘/‘, function (req, res) {

    // The posted information from the front-end
    var body = req.body;
    // Current time this occurred
    var time = moment().format(‘MMMM Do YYYY, h:mm:ss a‘);

    // Check to see if the user already exists
    // using their email address
    User.findOne({

        ‘email‘: body.email

    }, function (err, user) {

        // If there‘s an error, log it and return to user
        if (err) {

            // Nice log message on your end, so that you can see what happened
            console.log(‘Couldn\‘t create new user at ‘ + color.red(time) + ‘ by ‘ + color.red(body.email) + ‘ because of: ‘ + err);

            // send the error
            res.status(500).json({
                ‘message‘: ‘Internal server error from signing up new user. Please contact [email protected]‘
            });
        }

        // If the user doesn‘t exist, create one
        if (!user) {
            console.log(‘Creating a new user at ‘ + color.green(time) + ‘ with the email: ‘ + color.green(body.email));

            // setup the new user
            var newUser = new User({
                firstname: body.firstname,
                lastname: body.lastname,
                email: body.email,
                password: body.password1
            });

            // save the user to the database
            newUser.save(function (err, savedUser, numberAffected) {

                if (err) {
                    console.log(‘Problem saving the user ‘ + color.yellow(body.email) + ‘ due to ‘ + err);
                    res.status(500).json({
                        ‘message‘: ‘Database error trying to sign up.  Please contact [email protected]‘
                    });
                }

                // Log success and send the filtered user back
                console.log(‘Successfully created new user: ‘ + color.green(body.email));

                res.status(201).json({
                    ‘message‘: ‘Successfully created new user‘,
                    ‘client‘: _.omit(savedUser, ‘password‘)
                });

            });
        }

        // If the user already exists...
        if (user) {
            res.status(409).json({
                ‘message‘: body.email + ‘ already exists!‘
            });
        }

    });

});

// export the router for usage in our server/router/index.js
module.exports = router;

g.运行

cd server

Set NODE_ENV=development

npm test

http://localhost:3000/#/signup

7.Git代码库

https://github.com/hlxinyan/OnlineFoodOrdering.git

8.参考教程

http://start.jcolemorrison.com/building-an-angular-and-express-app-part-1/

http://start.jcolemorrison.com/building-an-angular-and-express-app-part-2/

http://start.jcolemorrison.com/building-an-angular-and-express-app-part-3/

时间: 2024-10-15 07:38:17

【Nodejs&&ExpressJS&&AngularJS】安装与框架搭建的相关文章

Angularjs和Ionic框架搭建webApp

本文原创版权归 简书作者 噜啦啦噜啦啦噜啦噜啦噜 所有,转载请联系作者获得授权,并于文章开头标注原创作者及出处,以示尊重! 文/噜啦啦噜啦啦噜啦噜啦噜(简书作者)原文链接:http://www.jianshu.com/p/ea0dcf1d31c9著作权归作者所有,转载请联系作者获得授权,并标注"简书作者". AngularJS简介:AngularJS 是一个为动态WEB应用设计的结构框架,提供给大家一种新的开发应用方式,这种方式可以让你扩展HTML的语法,以弥补在构建动态WEB应用时静

[AngularJS]项目框架搭建-MyFirst Skeleton

前文有提到过 做一个简单的订餐系统,最近花了点时间,了解了一下AngularJS框架的使用.因此本文的目的根据了解的知识重新搭建基于 AngularJS框架. 该框架是基于对于AngularJS的学习而制定的,这其中肯定有很多不足,在以后的学习中在加以改进. 一.系统准备 安装Node.js version>=0.10.0版本 Git  Shell 并添加该 Shell脚本到Path环境变量中  Path=:,"$git_home/bin"   二.手动搭建框架 2.1 创建开发

React第六篇: 搭建React + Router + antd + nodejs + express框架搭建(nodejs做前后端server)

前提: nodejs >= 10.0;  这里不推荐用官网的yarn安装antd的模块,因为后续会出错,错误如图: 也不推荐用npx方法来搭建react骨架,也会出错,让我们开始吧!!   前端React+Antd框架搭建 1.安装并启动create-react-app骨架应用 打开cmd按顺序执行以下指令: npm install -g create-react-app   (全局安装create-react-app, 默认会安装在C盘个人用户下) create-react-app my-ap

nodejs学习笔记一:安装express框架并构建工程目录

偶遇node是在一个阳光明媚的上午,无意间打开博客看到一片关于nodejs的介绍,通读全篇后,心情跌宕起伏,哎呀,这么好的东西我竟然现在才知道,这是最气的,于是马上开始制定学习nodejs计划,好了,话不多说,开始我的学习记录. 想要学习node首先开发环境不可少,下面就记录一下安装express框架和构建第一个node工程项目(跳过安装nodejs环境,因为已经装过,nodejs.org下载对应的安装包下一步傻瓜化安装): 1.安装express express是nodejs上最流行的web开

NodeJS学习笔记(一)——搭建开发框架Express,实现Web网站登录验证

JS是脚本语言,脚本语言都需要一个解析器才能运行.对于写在HTML页面里的JS,浏览器充当了解析器的角色.而对于需要独立运行的JS,NodeJS就是一个解析器.每一种解析器都是一个运行环境,不但允许JS定义各种数据结构,进行各种计算,还允许JS使用运行环境提供的内置对象和方法做一些事情.例如运行在浏览器中的JS的用途是操作DOM,浏览器就提供了document之类的内置对象.而运行在NodeJS中的JS的用途是操作磁盘文件或搭建HTTP服务器,NodeJS就相应提供了fs.http等内置对象.E

NodeJS+ExpressJS+SocketIO+MongoDB应用模板

OS:Win8.1 with update 关键字:NodeJS,ExpressJS,SocketIO,MongoDB. 1.源代码下载:https://github.com/ldlchina/ESMNodeAppTemplate 2.服务器环境配置: 安装NodeJS: http://www.nodejs.org/.安装mongodb: http://www.cnblogs.com/ldlchina/p/3551334.html.打开文件\lib\conf.json, 配置db选项.打开\pa

app.use 的作用 正则表达式中/ 表示什么 nodejs pm2 怎样安装 乱码怎么解决

app.use 的作用 正则表达式中/ 表示什么 nodejs pm2 怎样安装 乱码怎么解决 时间:2017-05-23 00:18:43      阅读:16      评论:0      收藏:0      [点我收藏+] 1.express 框架中的app.use是什么作用? 手册上写着是: app.use([path], function)Use the given middleware function, with optional mount path, defaulting to

基于Docker的TensorFlow机器学习框架搭建和实例源码解读

概述:基于Docker的TensorFlow机器学习框架搭建和实例源码解读,TensorFlow作为最火热的机器学习框架之一,Docker是的容器,可以很好的结合起来,为机器学习或者科研人员提供便捷的机器学习开发环境,探索人工智能的奥秘,容器随开随用方便快捷.源码解析TensorFlow容器创建和示例程序运行,为热爱机器学者降低学习难度. 默认机器已经装好了Docker(Docker安装和使用可以看我另一篇博文:Ubuntu16.04安装Docker1.12+开发实例+hello world+w

ASP.NET MVC+EF框架+EasyUI实现权限管理系列(1)-框架搭建

原文:ASP.NET MVC+EF框架+EasyUI实现权限管理系列(1)-框架搭建 ASP.NET MVC+EF框架+EasyUI实现权限管系列 (开篇) 前言:这篇博客开始我们便一步一步的来实现这个权限系统的初步设计-框架搭建,首先我要说的是我们需要开发工具Visual Studio 2012或者10也行,其次是我们要有SQL Server数据库,如果是Visual Studio 2010的话,你还要安装MVC4的开发文件,这个是吗?我不记得了,谁可以回答我一下的,我一直用2012,都是集成