2016-09-15 18 views
-1

これは私のコードブロックです。 APIエンドポイントjQuery ajaxとnodeJSの呼び出し

 app.get('/clients/zvb/:id', function(req, res) { 
console.log('ZVB Query loaded as var = file;') 
var path = './public/queries/zvb.sql' 
var zvb = fs.readFileSync(path, "utf8") 
zvb = zvb.splice(25, 0, req.params.id) 
request.query(zvb, function(err, recordset) { 
    console.log(recordset); 
    res.end(JSON.stringify(recordset)); 
}); 

})

私はエンドポイントからのデータを試してみて、GETその後、私のindex.htmlを。

 $.ajax({ 
    type: 'GET', 
    url: 'http://localhost:8081/clients/zvb/16601', 
    dataType: 'jsonp', 
    success: function(data) { 
     console.log(data); 
     console.log('we got to here..') 
    } 
}); 

現時点ではあまり起こっていません。ターミナルでAjaxコールを手動で実行しようとすると、

Object {readyState: 1} 

エンドポイントが動作していますが、私が見るとJSONが表示されます。トム

+0

です](http://expressjs.com/en/4x/api.html#res.jsonhttp://expressjs.com/en/4x/api.html#res.end)の代わりに[ res.end()](http://expressjs.com/en/4x/api.html#res.jsonhttp://expressjs.com/en/4x/api.html#res.end)。あなたのAjaxコールでは、 'jsonp'ではなく 'json'を期待してはいけませんか? –

+0

'dataType: 'jsonp'、なぜですか?あなたはjsonpが何であるか知っていますか? –

+0

'readFileSync'は、HTTPリクエストを受信するよりも、サーバー上でこのメソッドを使用しません。代わりに非同期バージョンを使用してください。 –

答えて

-1

あなたはjqueryのを使用している場合は、1.5以降これらの速記の方法は非常に使いやすいです。 (私はコメントできませんか、尋ねたでしょうか)。ドクは、ここであなたが[res.send()](http://expressjs.com/en/4x/api.html#res.send)または[res.json()すべきドキュメントからhttp://api.jquery.com/category/ajax/shorthand-methods/

$.get("http://localhost:8081/clients/zvb/16601", function(data) { 
    var data = JSON.parse(data); 
    }) 
    .done(function() { 

    }) 
    .fail(function() { 

    }) 
    .always(function() { 

    });