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:});
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跨域解决方案

Angular+NodeJs+MongoDB搭建前后端程序的更多相关文章

  1. 利用grunt-contrib-connect和grunt-connect-proxy搭建前后端分离的开发环境

    前后端分离这个词一点都不新鲜,完全的前后端分离在岗位协作方面,前端不写任何后台,后台不写任何页面,双方通过接口传递数据完成软件的各个功能实现.此种情况下,前后端的项目都独立开发和独立部署,在开发期间有 ...

  2. List多个字段标识过滤 IIS发布.net core mvc web站点 ASP.NET Core 实战:构建带有版本控制的 API 接口 ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目 Using AutoFac

    List多个字段标识过滤 class Program{  public static void Main(string[] args) { List<T> list = new List& ...

  3. 【手摸手,带你搭建前后端分离商城系统】01 搭建基本代码框架、生成一个基本API

    [手摸手,带你搭建前后端分离商城系统]01 搭建基本代码框架.生成一个基本API 通过本教程的学习,将带你从零搭建一个商城系统. 当然,这个商城涵盖了很多流行的知识点和技术核心 我可以学习到什么? S ...

  4. GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频)

    GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频) GraphQL + React Apoll ...

  5. 【手摸手,带你搭建前后端分离商城系统】02 VUE-CLI 脚手架生成基本项目,axios配置请求、解决跨域问题

    [手摸手,带你搭建前后端分离商城系统]02 VUE-CLI 脚手架生成基本项目,axios配置请求.解决跨域问题. 回顾一下上一节我们学习到的内容.已经将一个 usm_admin 后台用户 表的基本增 ...

  6. 【手摸手,带你搭建前后端分离商城系统】03 整合Spring Security token 实现方案,完成主业务登录

    [手摸手,带你搭建前后端分离商城系统]03 整合Spring Security token 实现方案,完成主业务登录 上节里面,我们已经将基本的前端 VUE + Element UI 整合到了一起.并 ...

  7. ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目

    一.前言 这几年前端的发展速度就像坐上了火箭,各种的框架一个接一个的出现,需要学习的东西越来越多,分工也越来越细,作为一个 .NET Web 程序猿,多了解了解行业的发展,让自己扩展出新的技能树,对自 ...

  8. python drf+xadmin+react+dva+react-native+sentry+nginx 搭建前后端分离的博客完整平台

    前言: 经过差不多半年的开发,搭建从前端到服务器,实现了前后端分离的一个集PC端.移动端的多端应用,实属不易,今天得空,好好写篇文章,记录这些天的成果.同时也做个分享. 演示网站地址: http:// ...

  9. 巨蟒python全栈开发flask8 MongoDB回顾 前后端分离之H5&pycharm&夜神

    1.MongoDB回顾 .启动 mongod - 改变data/db位置: --dbpath D:\data\db mongod --install 安装windows系统服务 mongod --re ...

随机推荐

  1. java 并发 concurrent Executor

    Excutor类 Executor 执行提交的对象Runnable任务. ExecutorService 一个Executor ,提供方法来管理终端和方法,可以产生Future为跟踪一个或多个异步任务 ...

  2. 末学者笔记--Linux网络模式及网卡配置

    一.linux网络的模式 三种模式:桥接,Nat和仅主机模式 一.桥接模式:配置桥接模式的虚拟机作为独立计算机存在 特点: 1. 虚拟机可以上外网2. 可以和局域网内任意一台电脑通信3. 可以和宿主机 ...

  3. Intellij Idea 2016创建web项目

    一.创建简单web项目 1.创建一个web project File -> new Project ->选择project sdk 为1.8(已经配过环境变量)其他不要选 -> Ne ...

  4. python全栈开发day102-django rest-framework框架

    1.频次访问组件 1) 手写版本 # class VisitThrottle(BaseThrottle): # # def __init__(self): # self.history = None ...

  5. logrotate命令

    logrotate是个十分有用的工具,它可以自动对日志进行截断(或轮循).压缩以及删除旧的日志文件,例如,你可以设置logrotate,让/var/log/foo日志文件每30天轮循,并删除超过6个月 ...

  6. Doctirne---查询更新等操作

    使用Doctrine进行mysql更删改查操作,事务处理,生命周期的管理 1.先记录最简单的插入操作 $em = $this->getDoctrine()->getManager(); / ...

  7. Facebook授权登录

    1.注册开发者账号 登陆facebook开发者平台 (https://developers.facebook.com/), 注册facebook开发者账号. 2.Facebook登录Key Hash配 ...

  8. Aspnet Mvc 前后端分离项目手记(一) 关于跨域问题(还有前言)

    前言,最近的项目使用前后端分离的模式,记录其中一些知识点.经过这个项目,也对前后端分离有了更多理解,尤其是在技术之外的方面. 越来越多的项目采用前后端分离的原因,有两点:      1,技术方面的原因 ...

  9. webpack配置css相关loader注意先后顺序

    一.问题描述 在webpack3中,引入animate.css失败. 二.问题分析 1.难道是入口main.js引用方式不对? import animate from 'animate.css' 2. ...

  10. Python学习笔记整理(python 3)

    一.tuple(元组) tuple和list非常类似,但是tuple一旦初始化就不能修改,如: classmates = ('Michael', 'Bob', 'Tracy') 1 classmate ...