2015-04-21 115 views
0

我在JS以下API:Nodejs和expressjs。阿贾克斯get请求不返回数据

router.route('/books') 
    .get(function(req,res){ 
     Repository.getAll().done(function(result){ res.json(result);},function(err){res.send(err);}); 
    }) 
    .post(function(req,res){ 
     Repository.save(req.body).done(function(object){ res.json(object); },function(err){res.send("error seems to have occured");}); 
    }); 

发帖时使用招,让使用Chrome浏览器工作正常。但是,当我尝试获取和使用jQuery后:

$.ajax({ 
           type: "POST", 
           url: "http://localhost:8000/api/books", 
           data: { "title":"My name is","releaseYear":"1989","director":"me","genre":"horror" } 
          }).done(function(data) { 
          //alert("Success."); 
          console.log("success"); 
         }).error(function(data, err, e, o) { 

          console.log("error"); 
          //alert("Sorry. Server unavailable. "); 
         }); 

          $.ajax({ 
           type: "GET", 
           url: "http://localhost:8000/api/books", 
           contentType: "application/json" 
          }).done(function(data) { 
          //alert("Success."); 
          console.log("success"); 
         }).error(function(data, err, e, o) { 

          console.log("error"); 
          //alert("Sorry. Server unavailable. "); 
         }); 

失败/错误回调被激发。我试过指定contentType或删除它,但无济于事。

当调用POST,状态代码是200,但没有数据返回,并调用失败功能

+1

您的请求调用“/ API /书”,你只能听“/书籍” – nada

+1

你有没有调试客户端和服务器的结果,以确保它有什么数据? –

+0

İlkerKorkut:调试服务器将是一个任务,因为之前从未调试节点。纳达:事实并非如此。我打电话的网址是正确的 – user1809104

回答

0

您是否尝试过加入dataType: "json"?在发布之前,您还应该尝试在对象上运行JSON.stringify()

2

您的请求调用“/ API /书”,你只能听“/书籍”

修改客户端代码请求网址是:

$.ajax({ 
           type: "POST", 
           url: "http://localhost:8000/books", 
           data: { "title":"My name is","releaseYear":"1989","director":"me","genre":"horror" } 
          }).done(function(data) { 
          //alert("Success."); 
          console.log("success"); 
         }).error(function(data, err, e, o) { 

          console.log("error"); 
          //alert("Sorry. Server unavailable. "); 
         }); 

          $.ajax({ 
           type: "GET", 
           url: "http://localhost:8000/books", 
           contentType: "application/json" 
          }).done(function(data) { 
          //alert("Success."); 
          console.log("success"); 
         }).error(function(data, err, e, o) { 

          console.log("error"); 
          //alert("Sorry. Server unavailable. "); 
         }); 

或修改服务器代码到:

router.route('/api/books') 
    .get(function(req,res){ 
     Repository.getAll().done(function(result){ res.json(result);},function(err){res.send(err);}); 
    }) 
    .post(function(req,res){ 
     Repository.save(req.body).done(function(object){ res.json(object); },function(err){res.send("error seems to have occured");}); 
    }); 
+0

也许他正在使用前缀路由器'app.use('/ api',router);'? –

+0

所以也许最好在他的问题中指定这个:D – nada

+0

要调用的正确url是:http:// localhost:8000/api/books。我使用前缀路由器。如上所述,这似乎可以在其他地方工作,但当使用jquery – user1809104