Angular+NodeJs+MongoDB搭建前后端程序
发布时间:2020-12-17 07:13:21 所属栏目:安全 来源:网络整理
导读:两种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
两种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/",response) { var heroName = request.query.name; console.log("name:" + request.query.name); heros.find({name:heroName},heros){ if(err) return console.error(err); response.send(heros); }); }); 通过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); }); ?另外,解决跨域问题: //后台设置跨域访问 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(); }); ?启动mongodb: mongod --dbpath d:/test 启动nodejs后端服务,通过nodemon启动,修改test.js代码后自动生效: nodemon test.js ? ? ? 参考: angular官方文档HTTPClient express官方文档request参数 mongoose官方文档 nodejs调试 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angular.js:4411 Uncaught Error: [$injector:modulerr]
- angularjs – 公共或私有 – Angular 2组件类方法混淆
- 你如何在Bash脚本中找到一个数字的阶乘?
- bash – 脚本全名和路径$0在调用时不可见
- WinForm/服务程序 调用 WebService 出现 无法识别的属性 de
- 将新入口点添加到泊坞窗图像
- twitter-bootstrap – 轻松查看Bootstrap网格的方法?
- twitter-bootstrap – 在Laravel 4中使用Bootstrap的最佳方
- 如何向bash守护进程发送自定义信号?
- WebService工作原理