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:});
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+NodeJs+MongoDB搭建前后端程序的更多相关文章
- 利用grunt-contrib-connect和grunt-connect-proxy搭建前后端分离的开发环境
前后端分离这个词一点都不新鲜,完全的前后端分离在岗位协作方面,前端不写任何后台,后台不写任何页面,双方通过接口传递数据完成软件的各个功能实现.此种情况下,前后端的项目都独立开发和独立部署,在开发期间有 ...
- 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& ...
- 【手摸手,带你搭建前后端分离商城系统】01 搭建基本代码框架、生成一个基本API
[手摸手,带你搭建前后端分离商城系统]01 搭建基本代码框架.生成一个基本API 通过本教程的学习,将带你从零搭建一个商城系统. 当然,这个商城涵盖了很多流行的知识点和技术核心 我可以学习到什么? S ...
- GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频)
GraphQL + React Apollo + React Hook + Express + Mongodb 大型前后端分离项目实战之后端(19 个视频) GraphQL + React Apoll ...
- 【手摸手,带你搭建前后端分离商城系统】02 VUE-CLI 脚手架生成基本项目,axios配置请求、解决跨域问题
[手摸手,带你搭建前后端分离商城系统]02 VUE-CLI 脚手架生成基本项目,axios配置请求.解决跨域问题. 回顾一下上一节我们学习到的内容.已经将一个 usm_admin 后台用户 表的基本增 ...
- 【手摸手,带你搭建前后端分离商城系统】03 整合Spring Security token 实现方案,完成主业务登录
[手摸手,带你搭建前后端分离商城系统]03 整合Spring Security token 实现方案,完成主业务登录 上节里面,我们已经将基本的前端 VUE + Element UI 整合到了一起.并 ...
- ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目
一.前言 这几年前端的发展速度就像坐上了火箭,各种的框架一个接一个的出现,需要学习的东西越来越多,分工也越来越细,作为一个 .NET Web 程序猿,多了解了解行业的发展,让自己扩展出新的技能树,对自 ...
- python drf+xadmin+react+dva+react-native+sentry+nginx 搭建前后端分离的博客完整平台
前言: 经过差不多半年的开发,搭建从前端到服务器,实现了前后端分离的一个集PC端.移动端的多端应用,实属不易,今天得空,好好写篇文章,记录这些天的成果.同时也做个分享. 演示网站地址: http:// ...
- 巨蟒python全栈开发flask8 MongoDB回顾 前后端分离之H5&pycharm&夜神
1.MongoDB回顾 .启动 mongod - 改变data/db位置: --dbpath D:\data\db mongod --install 安装windows系统服务 mongod --re ...
随机推荐
- const与#define的异同
1 作为常量时的异同 (0) 相同 两者都可以用来定义常量: #define PI 3.14159 // 常量宏 const doulbe Pi=3.14159; // 常量 (1) ...
- 获取元素属性get_attribute
获取text # coding:utf-8 from appium import webdriver from time import sleep desired_caps = { 'platform ...
- 【winform】datagridview获取当前行停留时间
RowStateChanged 的问题 RowStateChanged事件,也就是行状态发生变化时触发的事件,这个事件无法实现行号变化而触发这个要求,因为当我们从一行选择至另一行时,先触发原行号的状态 ...
- [原创]基于Zynq AXI-Bram Standalone & Linux 例程
基于Zynq AXI-Bram Standalone & Linux 例程 待添加完善中
- neo4j 学习笔记
1.参考 https://blog.csdn.net/appleyk/article/category/7408344 系列文章 (不支持 spring boo 2.0 以下的,入门可做参考) 2.底 ...
- Linux基础系统优化
Linux的网络功能相当强悍,一时之间我们无法了解所有的网络命令,在配置服务器基础环境时,先了解下网络参数设定命令. ifconfig 查询.设置网卡和ip等参数 ifup,ifdown 脚本命 ...
- 五一劳动节,讲讲NEO智能合约的调试
之前我们说过NEO智能合约的调试问题,过去了一段时间,有很多东西都发生了比较大的变化.让我们重新再来探讨一下这个话题. 先说日期,2018年4月27日,马上迎来劳动节. 以后可能还会再次谈论这个话 ...
- 02-Python入门学习-变量
一.编程语言介绍1.机器语言:直接用二进制编程,直接控制硬件,需要掌握硬件的操作细节优点:执行效率高缺点:开发效率低 2.汇编语言:用英文标签取代二进制指令去编写程序,直接控制硬件,需要掌握硬件的操作 ...
- JavaFile I/O
Java流类图结构: 流的概念和作用: 流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象.及数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将抽象为各种类,方便更直观 ...
- haskell实现简易计算器
> module Main where > import System.IO > import Data.Char > import Control.Monad > im ...