簡體   English   中英

Node.js Express | jQuery在獲取JSON時客戶端沒有任何反應

[英]Node.js Express | JQuery Nothing happens on client when getting a JSON

我想在HTML5網站上從PostgreSQL數據庫接收JSON。 因此,在服務器端,我使用node-postgres模塊進行數據庫連接,並使用express模塊​​進行通信。

問題是在html中,從服務器獲取數據時我沒有看到任何警報。 該警報甚至沒有引發。

到目前為止,這是我的代碼的樣子,對於任何可以幫助的人:

服務器端

var express = require('express');
var app = express();

app.get('/data', function(req, res){
   var pg = require('pg'); 

            var conString = "postgres://postgres:postgres2@localhost/spots";

            var client = new pg.Client(conString);
            client.connect(function(err) {
              if(err) {
                res.send('could not connect to postgres');
              }
              client.query('SELECT * from spots_json where id=3276', function(err, result) {
                if(err) {
                 res.send('error running query'); 
                }
                res.set("Content-Type", 'text/javascript'); // i added this to avoid the "Resource interpreted as Script but transferred with MIME type text/html" message
                res.send(JSON.stringify(result.rows[0].json));
                              client.end();
              });
            }); 

});

app.listen(3000);

客戶端

<!DOCTYPE html>
<html>
  <head>
    <title>Test</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"></meta>
    <meta charset="utf-8"></meta>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" ></script>

    <script>

   $.get('http://localhost:3000/data?callback=?',{}, function(data){
       alert(data.type); 
   },"json");                  

    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

客戶端現在在http://localhost:8888/prueba/prueba.html

我正在使用以下響應獲取js:

"{\"type\":\"Point\",\"coordinates\":[-2.994783,43.389217]}"

可以在以下屏幕截圖中看到響應:

https://www.dropbox.com/s/zi4c5pqnbctf548/pantallazo.png

result.rows[0].json不是對象,而是字符串。 你並不需要stringify它:

res.send(result.rows[0].json);

編輯:

如果您在不同端口上使用兩台服務器,則需要使用JSONP。 jQuery在客戶端使這一過程變得簡單,但是您將需要在服務器中實現它( 例如 ):

if(req.query.callback) {
  res.send(req.query.callback + '(' + result.rows[0].json + ');');
} else {
  res.send(result.rows[0].json);
}

順便說一句,如果您在一個回調中遇到錯誤,則需要return以防止執行后續代碼。

if(err) {
  res.end('error message');
  return;
  // Or shorter: return res.end('error message');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM