2017-08-24 16 views
0

私はルータにajaxリクエストをしています。そのルータはデータベース内のデータを見つけ出し、同じページに戻ります。しかし、データベースオブジェクトを取得する代わりに、クライアント側のコンソールにhtmlページ全体が表示されます。サーバ側では適切なオブジェクトを取得します。私は他の人に同様の質問をしましたが、答えを見つけることができませんでした。助けていただければ幸いです。あなたがクライアントにレンダリングされたHTML文字列を返します応答を送信するためにres.renderを使用しているので、それがあるhtmlページ(ExpressJS)全体を印刷するAjaxリクエスト

$(document).ready(function(){ 
    $('#target').click(function (e) { 
     e.preventDefault(); 

     function successCallback(responseObj){ 
      console.log(responseObj); 
     }; 

     $.ajax({ 
      url: "https://stackoverflow.com/users/usuario/receber", 
      type: "get", 
      success: function(response){ 
       successCallback(response); 
      } 
     }); 
    }); 
}); 

答えて

0

マイルータ:

router.get('/usuario/receber', function(req, res) { 
     Redacao 
     .findOne({}) 
     .then(doc => {console.log(doc), res.render('usuario', doc)}) 
     .catch(err => { 
      console.log(err); 
      res.status(500).send({ message: err }); 
     }); 
}); 

私の見解。代わりにJSON文字列を使用して返信したい場合は、res.json

router.get('/usuario/receber', function(req, res) { 
     Redacao 
     .findOne({}) 
     .then(doc => {console.log(doc), res.json(doc)}) 
     .catch(err => { 
      console.log(err); 
      res.status(500).send({ message: err }); 
     }); 
}); 
+0

ありがとうございました! –

関連する問題