express项目初始配置

2019-03-03  本文已影响0人  bayi_lzp

1.新建express项目

1.全局安装express

cnpm i -g express-generator

2.新建express目录

express sever

3.进入sever目录下bin启动www

node bin/www

另: 把jade模板引擎换为html

1.安装ejs插件, cnpm i ejs --save

2.在app.js中加入app.engine('.html', ejs.__express)

3.引入ejs ``` ver ejs = require("ejs")

4.把app.set('view engine','jade')换为 app.set('view engine', 'html')

2.express连接用mongoose连接mongoDB数据库

1.安装mongoose,cnpm i mongoose --save ,在router中新建路由文件,例如goods.js,编写内容

var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var Goods = require('../models/goods')

// 连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/mall')

mongoose.connection.on('connected', function () {
  console.log("连接成功");
})

mongoose.connection.on('error', function () {
  console.log('连接失败');
})

mongoose.connection.on('disconnected', function () {
  console.log('断开连接');
})

router.get('/', function (req, res, next) {
  Goods.find({}, function (err, doc) {
    if (err) {
      res.json({
        status: '1',
        msg: err.message
      })
    } else {
      res.json({
        status: "0",
        msg: '',
        result: {
          count: doc.length,
          list: doc
        }
      })
    }
  })
})
module.exports = router

2.在app.js文件中引入该文件

var goodsRouter = require('./routes/goods');

app.use('/goods', goodsRouter);

3.新建models文件夹,新建goods.js文件,编写js

var mongoose = require('mongoose')
var Schema = mongoose.Schema

var productSchema = new Schema({
    // 字段
  "productId": String,
  "productName": String,
  "salePrice": Number,
  "productImage": String
})

module.exports = mongoose.model('goods',productSchema)

3.配置客户端支持跨域请求

在app.js文件中加入一下代码,放在请求路由前面

//设置跨域访问
    
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

上一篇下一篇

猜你喜欢

热点阅读