我有一个 Node 应用程序,它将不同类型的类(class)插入 mongodb 并直接从数据库将它们显示到网页上。我想使用 fetch() api 函数从 mongodb 获取数据,将数据传递为 json 格式,然后使用 ejs 引擎显示它们
mongoose.connect('mongodb://localhost:27017/studentdb')
var db=mongoose.connection;
db.on('error', console.log.bind(console, "connection error"));
db.once('open', function(callback){
console.log("connection succeeded");
})
app.get('/', function(req, res, next) {
// fetch and sort course collection by id in descending order
req.db.collection('course').find().sort({"_id": -1}).toArray(function(err, result) {
//if (err) return console.log(err)
if (err) {
req.flash('error', err)
res.render('user/list', {
title: 'User List',
data: ''
})
} else {
// render to views/user/list.ejs template file
res.render('user/list', {
title: 'User List',
data: result
})
}
})
})
// SHOW ADD course FORM
app.get('/add', function(req, res, next){
// render to views/user/add.ejs
res.render('user/add', {
title: 'Add course',
topic: '',
price: '',
location: '',
provider:'',
review_rankings: '',
author_ranking: ''
})
})
app.post('/add', function(req,res, next){
var topic = req.body.topic;
var price =req.body.price;
var location = req.body.location;
var provider = req.body.provider;
var review_rankings = req.body.review_rankings;
var author_ranking =req.body.author_ranking;
var data = {
"topic": topic,
"price":price,
"location":location,
"provider":provider,
"review_rankings":review_rankings,
"author_ranking": author_ranking
};
db.collection('course').insertOne(data,function(err, collection){
if (err) throw err;
console.log("Record inserted Successfully");
});
return res.redirect('/users');
})
我想使用 fetch api 函数,如下面的代码,使用 mongodb 并将信息显示到网页
fetch('http"//reqres.in./api/users', {
method:'POST',
headers:{
'content-type': 'application/json'
},
body: JSON.stringify({
name:'user 1'
})
}).then(res => {
return res.json()
})
.then(data => console.log(data))
.catch(error => console.log('ERROR'))
最佳答案
NodeJS 应用程序无法立即使用 fetch API。您可以使用node-fetch
包来获取类似的API(尽管有一些known differences),或使用其他库,例如Axios。
不使用外部包的解决方案是使用 native http
模块(使用文档 here 中的 request
方法)
关于node.js - 使用fetch api函数从MongoDB获取数据并在node.js中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59863159/