mercredi 6 mai 2015

sending requests to my own API to make changes to DB which is not being updated. I would like the DB to be updated

Im having trouble understanding how to make request to an API that was set up with express to do CRUD methods. in the below code .get(/bears) renders a form and in the app.post('/bears') i'm using the nPmodule 'request' to send the request to the api/bears router by doing this i expect name attr of the text box which is the same field on the db to be added to the db (bear.save(function(err){ )It doesn't that is the problem.

someone please show me how to make calls from a route(page) to the api so the api could update the db from the form in the html from the view.

I think Angular has services for this but I want to see how to do this with express. Is there away to do it with out the npm request?

js fiddle with more of the code

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

})

Aucun commentaire :

Enregistrer un commentaire