gpt4 book ai didi

node.js - 无法使用 Express API 和 Node JS(Angular4) 将数据发布到 mongo db

转载 作者:太空宇宙 更新时间:2023-11-03 22:07:23 24 4
gpt4 key购买 nike

我已经使用express API和node js成功完成从MongoDB获取数据并将其绑定(bind)到 Angular ng2-smart-table。单击表的添加按钮时,我正在调用 Express API,但 api.js 中未调用我的 post 方法,我尝试在 post 中打印 console.log 但未调用它。为了更好地理解,我发布代码:

Component.ts

onCreateConfirm(event,_dataService): void {          
this._dataService.postMutualFunds(event.newData);
event.confirm.resolve(event.newData);
}

data.service.ts

postMutualFunds(parameterValue:any ){
return this._http.post('/add_mutual_funds',
{params:parameterValue}).map(result => this.result = result.json().data);
}

api.js

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var bodyParser = require("body-parser");

const connection = (closure) => {
return
MongoClient.connect('mongodb://xxx.com:63898/xx', (err,db) => {
if(err){
return console.log(err);
}
closure(db);
});
}
//Get call
router.get('/mutual_funds',(req,res) =>{
console.log("test get"); //This is executed
connection((db) => {
var projection = {_id:0};
db.collection('mutual_funds').find().project(projection).
toArray().then((mutual_funds) => {
response.data = mutual_funds;
res.json(response);
})
})
})

//Post call
router.post('/mutual_funds',(req,res) => {
console.log(req.body.params);
console.log("test post");
db.collection('mutual_funds').insertOne(req.body.params)
})

module.exports = router;

enter image description here

现在我可以调用 api js,但无法将数据插入 mongodb 请找到下面 api.js 执行输出的屏幕截图//为什么我无法发布数据?(更新了上面的发布代码)遇到错误 500

enter image description here

enter image description here

最佳答案

您没有订阅该服务

onCreateConfirm(event,_dataService): void {          
this._dataService.postMutualFunds(event.newData).subscribe(
(data)=>{
console.log(data)
},
(err)=>{
console.log(err)
}
)
event.confirm.resolve(event.newData);
}

The service method returns an Observable of configuration data, the component subscribes to the method's return value. The subscription callback copies the data fields into the component's config object, which is data-bound in the component template for display.

关于node.js - 无法使用 Express API 和 Node JS(Angular4) 将数据发布到 mongo db,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51936126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com