2015-05-06 62 views
3

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

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

我觉得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) 
    }) 

}) 

回答

0

这似乎是工作。我不知道我可以把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'); 
})