2016-03-22 75 views
-1

我有NodeJS作爲後端通過localhost提供來自MySQL的JSON數據:3002/visit;我想讓Angular2從我的NodeJS中獲取JSON。 問題是,雖然我的Angular2應用程序可以從在線JSON API服務中完全抓取JSON,但是在將URL GET切換到localhost:3002/visit時,它在訂閱時出錯。Angular2無法從NodeJS獲取數據

的NodeJS:

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

var app = express(); 
var connection = mysql.createConnection({ 
    host  : 'localhost', 
    user  : 'root', 
    password : 'angela', 
    database : 'emergency', 
}); 

connection.connect(function(err){ 
if(!err) { 
    console.log("Database is connected ... nn");  
} else { 
    console.log("Error connecting database ... nn");  
} 
}); 

app.get('/patient',getAllFromPatient); 
app.get('/staff', getAllFromStaff); 
app.get('/visit', getAllFromVisit); 

function getAllFromPatient(req,res){ 
    connection.query('SELECT * from patient', function(err, rows, fields) { 
    if (!err) 
     res.send(rows); 
    else 
     console.log('Error while performing Query.'); 
});} 

function getAllFromStaff(req,res){ 
    connection.query('SELECT * from staff', function(err, rows, fields) { 
    if (!err) 
     res.send(rows); 
    else 
     console.log('Error while performing Query.'); 
});} 

function getAllFromVisit(req,res){ 
    connection.query('SELECT * from visit', function(err, rows, fields) { 
    if (!err){ 
     res.send(rows); 
     console.log("visit data sent"); 
     }else 
     console.log('Error while performing Query.'); 
});} 

app.listen(3002); 

角2:

return this.http.get("http://localhost:3002/visit") 
.map(res => res.json()) 
.subscribe(
     data => this.msg = JSON.stringify(data), 
     err => alert(err), 
     () => console.log("complete") 
    ); 
+2

你能更具體地瞭解「錯誤」嗎? – qqilihq

+0

只是一個瘋狂的猜測 - 你有嘗試過使用Response的'json()'方法而不是'send()'嗎? – rrjohnson85

回答

1

Angular2需要知道的是,接收到的內容是一個JSON一個。因此,在這種情況下,application/json值的Content-Type標頭必須存在於響應標頭中。

要做到這一點,你需要要麼:

  • 手動設置Content-Type頭:

    function getAllFromVisit(req,res){ 
        connection.query('SELECT * from visit', function(err, rows, fields) { 
        if (!err){ 
         res.setHeader("Content-Type", "application/json"); 
         res.send(rows); 
         console.log("visit data sent"); 
        }else 
         console.log('Error while performing Query.'); 
        }); 
    } 
    
  • 使用json方法而不是做同樣的事情:

    function getAllFromVisit(req,res){ 
        connection.query('SELECT * from visit', function(err, rows, fields) { 
        if (!err){ 
         res.json(rows); 
         console.log("visit data sent"); 
        }else 
         console.log('Error while performing Query.'); 
        }); 
    }