【问题标题】:using fetch api function to get data from MongoDB and display them in node.js使用 fetch api 函数从 MongoDB 获取数据并在 node.js 中显示它们
【发布时间】:2020-05-08 19:35:19
【问题描述】:

我有一个节点应用程序,它将不同类型的课程插入到 mongodb 中,并将它们直接从数据库显示到网页上。我想使用 fetch() api 函数通过将数据传递为 json 格式然后使用 ejs 引擎显示它们来从 mongodb 获取数据

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'))

【问题讨论】:

    标签: node.js mongodb express fetch


    【解决方案1】:

    获取 API 不适用于 NodeJS 应用程序。您可以使用 node-fetch 包来获取类似的 API(虽然有一些 known differences),或者使用其他库,如 Axios。

    不使用外部包的解决方案是使用本机http 模块(使用request 记录的here 方法)

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 2019-03-12
      • 1970-01-01
      • 2021-04-22
      • 2018-03-11
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多