【问题标题】:sending requests to my own API to make changes to DB which is not being updated. I would like the DB to be updated向我自己的 API 发送请求以更改未更新的数据库。我想更新数据库
【发布时间】:2015-07-16 04:52:21
【问题描述】:

我无法理解如何向使用 express 设置的 API 发出请求以执行 CRUD 方法。在下面的代码中.get(/bears) 呈现一个表单,在app.post('/bears') 我使用 nPmodule 'request' 通过这样做将请求发送到 api/bears 路由器,我希望文本框的名称 attr 是相同的要添加到数据库的数据库上的字段(bear.save(function(err){)这不是问题所在。

请有人告诉我如何从路由(页面)调用 api,以便 api 可以从视图中的 html 表单中更新 db。

我认为 Angular 有这方面的服务,但我想看看如何使用 express 来做到这一点。如果没有 npm 请求,是否可以这样做?

js fiddle 更多代码

app.get('/bears', function(req, res){
   res.render('index', {message : "You are rendered!"});     
})
app.post('/bears', function(req, res){
// request.post('http://localhost:8080/api/bears',function(error, response, body){
//  if(!error && response.statusCode == 200){
//      var info = JSON.parse(body)
//      res.send(info);
//  }else{
//      res.send(error);
//  }
// })
   request.post('http://localhost:8080/api/bears', function(error, response, body){
      console.log(body);
      console.log(response)
   })


})

router.route('/bears')
.post(function(req, res){
    var bear = new Bear();
    bear.name = req.body.name;

    bear.save(function(err){
        if(err)
            res.send(err);

        res.json({message : 'Bear created!'});
    })
})
.get(function(req, res){

    Bear.find(function(err, bears){
        if(err)
            res.send(err);
        res.json(bears);
        console.log(bears[0].id)
    })

})

【问题讨论】:

    标签: javascript node.js api express


    【解决方案1】:

    这似乎有效。我不知道我可以把req.body.name 作为一个“价值”

    request form documentation

     app.post('/bears', function(req, res){
    // request.post('http://localhost:8080/api/bears',function(error, response, body){
    //  if(!error && response.statusCode == 200){
    //      var info = JSON.parse(body)
    //      res.send(info);
    //  }else{
    //      res.send(error);
    //  }
    // })
    request.post({url : 'http://localhost:8080/api/bears', form : {name : req.body.name }}, function(err, httpResponse, body){
        res.redirect("/alpha");
    })
    
    
    })
    app.get('/alpha', function(req, res){
    res.send('It was updated');
    })
    

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2022-08-15
      • 1970-01-01
      • 2018-01-14
      相关资源
      最近更新 更多