Angular+NodeJs+MongoDB搭建前后端程序

get请求:

//angular 前端get请求
this.client.get('http://localhost:3000/id/tom').subscribe(data => {
      console.log(data);
    });

//nodejs后端响应
app.get("/id/:name", function (request, response) {
    var heroName = request.params.name;
    //debugger;
    console.log("name:" + request.params.name);
    heros.find({name:heroName},function(err,heros){
      if(err) return console.error(err);
      response.send(heros);
    });
    
});

另一种:

// client: HttpClient : @angular/common/http 
this.client.get('http://localhost:3000/id', { params: { name: 'tom' } }).subscribe(data => {
      console.log(data);
    });

//var express = require("express");  var app = express();
app.get("/id/", function (request, response) {
    var heroName = request.query.name;  
    console.log("name:" + request.query.name);
    heros.find({name:heroName},function(err,heros){
      if(err) return console.error(err);
      response.send(heros);
    });
    
});

post:

//angular发送post请求
this.client.post<Hero>('http://localhost:3000/hero', hero)
        .subscribe(data => {
          console.log(data);
});

//后台处理post请求
app.post("/hero", function (request, response) {
    var theHero = new heros({name:'',race:[],price:1});
    console.log('theHero:' + theHero);
    // theHero.save(function (err, data) {
    //  if (err) return console.error(err);
    //  response.send("post:" + theHero);
    // });
 
});  

 

通过Mongoose连接MongoDB,并进行查询和保存数据:

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/hero',{config:{autoIndex:false}}); // 进入mongo命令行 show dbs 将看到hero
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("connection success");
});

var heroSchema = new  mongoose.Schema({
  name:String
});
heroSchema.set('autoIndex',false);

heroSchema.methods.display = function () {
  console.log(this.name);
}

var Hero = mongoose.model('heros', heroSchema); //show collections 将看到heros

// 通过model 查询; 在mongo命令行 使用 db.heros.find({name:'tom'})
Hero.find({name:'tom'},function(err,heros){
      if(err) return console.error(err);
      console.log(heros);
});

//通过model创建theHero并保存到mongodb 
var theHero = new Hero ({ name: 'tom' });
theHero.save(function (err, data) {
    if (err) return console.error(err);
 });
    

 另外,解决跨域与请求带HttpHeaders报错问题:

//后台设置跨域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow- Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("Access-Control-Allow-Headers", "Content-Type,Access-Token");
    res.header("Access-Control-Expose-Headers","*");
next(); //必须有 });

 启动mongodb:

mongod --dbpath d:/test

启动nodejs后端服务,通过nodemon启动,修改test.js代码后自动生效:

nodemon test.js   

后台代码:

var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var multer = require('multer'); 
var upload = multer();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/hero',{config:{autoIndex:false}});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("connection success");
});

var heroSchema = new  mongoose.Schema({
  name:String,
  race:[String],
  price:Number
});

heroSchema.set('autoIndex',false);

heroSchema.methods.display = function () {
  var msg = this.name + ":" + this.race.join(",") + ":" + this.price;   
  console.log(msg);
}

var heros = mongoose.model('heros', heroSchema);

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

app.get("/id/:name", function (request, response) {
    var heroName = request.params.name;
    debugger;
    console.log("name:" + request.params.name);
    heros.find({name:heroName},function(err,heros){
      if(err) return console.error(err);
      response.send(heros);
    });
    
});

app.get("/id", function (request, response) {
    var heroName = request.query.name;  
    console.log("name:" + request.query.name);
    heros.find({name:heroName},function(err,heros){
      if(err) return console.error(err);
      response.send(heros);
    });
    
});

app.post("/hero",upload.array(), function (request, response) {
    var param = request.body;
    const theHero = new heros({name:param.name,race:param.race,price:param.price});
    console.log('theHero:' +  param.name);

    theHero.save(function (err, data) {
       if (err) return console.error(err);
       response.send({'data':'ok'});
    });
 
});   

 app.listen(3000);

 

 

 

参考:

angular官方文档HTTPClient

express官方文档request参数

mongoose官方文档

nodejs调试

HttpHeader无法发送

ajax跨域解决方案

转载于:https://www.cnblogs.com/yongwangzhiqian/p/10361371.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值