Angular2无法从NodeJS获取数据

时间:2016-03-22 19:47:40

标签: node.js localhost angular

我有NodeJS作为后端,通过localhost提供来自MySQL的JSON数据:3002 / visit;我想让Angular2从我的NodeJS中获取JSON。 问题是我的Angular2应用程序可以完全从在线JSON API服务中获取JSON,当我将URL GET切换到localhost:3002 / visit时,它在订阅时出错。

的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);

Angular 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")
    );

1 个答案:

答案 0 :(得分:1)

Angular2需要知道收到的内容是JSON版本。因此,在这种情况下,响应标头中必须包含带有Content-Type值的application/json标头。

要做到这一点,你需要:

  • 手动设置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.');
      });
    }