【问题标题】:Angular Nodejs : Output is Undefined, Can't access the data from the serverAngular Nodejs:输出未定义,无法从服务器访问数据
【发布时间】:2019-05-26 19:15:12
【问题描述】:

我刚刚开始使用 Node 和 Angular 进行编程,我正在尝试运行一个简单的应用程序,其中我将后端 (localhost:3000) 连接到前端并显示数据。如果我在发出 get 请求时从服务器接收到的数据放在一个 .json 文件中,并且我在同一个文件夹中访问它,那么就会显示数据。

但是,如果我使用从中提取数据的 api(http://localhost:3000/purchase) 地址,我会在浏览器中收到未定义的错误。

这是它在浏览器中显示的错误:

ContactsComponent.html:2 ERROR TypeError: Cannot read property 'Empno' of undefined
    at Object.eval [as updateRenderer] (ContactsComponent.html:2)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:22503)
    at checkAndUpdateView (core.js:21878)
    at callViewAction (core.js:22114)
    at execComponentViewsAction (core.js:22056)
    at checkAndUpdateView (core.js:21879)
    at callViewAction (core.js:22114)
    at execComponentViewsAction (core.js:22056)
    at checkAndUpdateView (core.js:21879)
    at callWithDebugContext (core.js:22767)

这是我在 Postman 上的服务器 (http://localhost:3000/purchase) 的输出:

{
    "Empno": "113       ",
    "Ename": "Mary      ",
    "Sal": "15220     ",
    "Deptno": "DP        "
}

这是服务的角度代码:

import { Injectable } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
import { map, filter, switchMap, catchError } from 'rxjs/operators';
import { Contact } from './contact';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry } from 'rxjs/operators';



@Injectable({
  providedIn: 'root'
})

export class ContactService {
  contact: Contact[];
  //  configUrl1 = '../assets/test.json';
 configUrl1 = 'http://localhost:3000';


  constructor(private http: HttpClient) { }
  // retrieving contacts

  getPurchase() {
    return this.http.get(this.configUrl1);
  }

}

**This is the code for the Component:**

import { Component, OnInit } from '@angular/core';
import {  ContactService } from '../contact.service';
import { Contact } from '../contact';


@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.scss'],
  providers: [ContactService]
})
export class ContactsComponent implements OnInit {
  contact: Contact;
  Empno: string;
    Ename: string;
    Sal: string;
    Deptno: string;


  constructor(private contactService: ContactService) { }

  ngOnInit() {
    this.contactService.getPurchase()
      .subscribe((data: Contact) => this.contact = {...data});
    }

}

这是定义联系人结构的代码:

export class Contact {
    Empno: string;
    Ename: string;
    Sal: string;
    Deptno: string;
    }

这是联系人组件的 HTML 文件的代码:

<div class= "container">
  <p>Its Working here also</p>

    {{contact.Empno}}
    {{contact.Ename}}

</div>

服务器端代码: App.js

//importing modules
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var mssql = require('mssql');
var path = require('path');
var app = express();

const route = require('./routes/route');
//port no
const port = 3000;

// adding middlewear - cors
app.use(cors());

// adding middlewear - bodyparser
// app.use(bodyparser.json());

// static files
app.use(express.static(path.join(__dirname, 'public')));

//creating routes
app.use('/purchase', route);

//testing 
app.get('/', (req,res)=>{
    res.send('foobar');
});

// //bind the port
app.listen(port, () => {
  console.log('Server started at port: ' + port);
});

// create application/json parser
var jsonParser = bodyParser.json()
// app.use(bodyParser.json({ type: 'application/*+json' }))

// POST /login gets urlencoded bodies
app.post('/login', jsonParser, function (req, res) {
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

route.js

const express = require('express');
const router = express.Router();
var bodyParser = require('body-parser');
var app = express();
const sql = require('mssql');
const config = 'mssql://vpn:vpn1@ASPL-AVG:1433/Sampledb';


app.use(bodyParser.json());

var jsonParser = bodyParser.json()

router.get('/', jsonParser,(req,res, next)=>{
  var conn = new sql.ConnectionPool(config);
  conn.connect().then((conn) => {
    var sqlreq = new sql.Request(conn);
    sqlreq.execute('SelEmpl10', function(err, recordset) {
      res.json(recordset.recordsets[0][1]);
      console.log(recordset.recordsets[0][1]); 

    })
    })
  });

//add purchase order
router.post('/' , jsonParser ,(req, res, next) => {
    //logic to add record
    console.log(req.body.username);
    var conn = new sql.ConnectionPool(config);
    conn.connect().then((conn) => {
      var sqlreq = new sql.Request(conn);
      sqlreq.input('Username', sql.VarChar(30), req.body.username);
      sqlreq.input('Password', sql.VarChar(30), req.body.password);
      sqlreq.input('Email', sql.VarChar(30), req.body.email);
      sqlreq.input('Name', sql.VarChar(30), req.body.name);
      sqlreq.execute('saveuser').then(function(err, recordsets, returnValue, affected) {
        console.dir(recordsets);
        console.dir(err);
        conn.close();
      }).catch(function(err) {
            res.json({msg: 'Failed to add contact'});
            console.log(err);
      });
    });
  })



//delete purchase order
router.delete('/:id', (req, res, next) => {
    //logic to delete record

});

module.exports = router;  

从 SQL 收到的数据是这样的:

{
    "recordsets": [
        [
            {
                "Empno": "112       ",
                "Ename": "john      ",
                "Sal": "142500    ",
                "Deptno": "CS        "
            },
            {
                "Empno": "113       ",
                "Ename": "Mary      ",
                "Sal": "15220     ",
                "Deptno": "DP        "
            }
        ]
    ],
    "recordset": [
        {
            "Empno": "112       ",
            "Ename": "john      ",
            "Sal": "142500    ",
            "Deptno": "CS        "
        },
        {
            "Empno": "113       ",
            "Ename": "Mary      ",
            "Sal": "15220     ",
            "Deptno": "DP        "
        }
    ],
    "output": {},
    "rowsAffected": [
        2
    ],
    "returnValue": 0
}

在Node中添加参数后输出是这样的:

{
    "Empno": "113       ",
    "Ename": "Mary      ",
    "Sal": "15220     ",
    "Deptno": "DP        "
}

【问题讨论】:

  • contact 在组件初始加载时未定义,这将导致未定义错误。使用异步管道或使用 ngIf 仅在实际加载联系人时呈现 div。
  • 我添加了另一个
    现在我收到错误:Message: "Http failure during parsing for http://localhost:3000/" name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: "http://localhost:3000/"
  • 请逐步复现,我们试试看:this.contactService.getPurchase() .subscribe((data) =&gt; { console.log(data); }); } 校验值是字符串还是变量
  • @ThienHoang 它给了我与上面相同的错误。由于某种原因没有收到数据。

标签: node.js angular rxjs


【解决方案1】:

此问题可能与bodyParser 的使用有关。它可能正在尝试解析已解析的 JSON。基本上在顶层添加一次解析器并将其从路由中删除。它也可以连接到使用 json() 而不是 send()。我遇到过问题,如果数据有一个名为 data 的属性,它可能会导致 json parse/stringify 失败。

试试下面的。在App.js 中重新引入app.use(bodyParser.json()) 行,这只需要在顶级位置添加一次,例如此条目文件。同样从此文件中删除 jsonParser 中间件从 /login POST 路由:

var bodyParser = require('body-parser');
var app = express();

const route = require('./routes/route');
//port no
const port = 3000;

// adding middlewear - cors
app.use(cors());

// adding middlewear - bodyparser
app.use(bodyParser.json());

// static files
app.use(express.static(path.join(__dirname, 'public')));

//creating routes
app.use('/purchase', route);

//testing 
app.get('/', (req,res)=>{
    res.send('foobar');
});

// //bind the port
app.listen(port, () => {
  console.log('Server started at port: ' + port);
});

// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
  if (!req.body) return res.sendStatus(400)
  res.send('welcome, ' + req.body.username)
})

route.js 中,删除bodyParser.json()jsonParser 中间件,它已经包含在顶层,因为app.use(bodyParser.json()); 将其应用于所有 路由/动词:

const express = require('express');
const router = express.Router();
var app = express();
const sql = require('mssql');
const config = 'mssql://vpn:vpn1@ASPL-AVG:1433/Sampledb';

router.get('/',(req, res, next)=>{
  var conn = new sql.ConnectionPool(config);
  conn.connect().then((conn) => {
    var sqlreq = new sql.Request(conn);
    sqlreq.execute('SelEmpl10', function(err, recordset) {
      res.json(recordset.recordsets[0][1]);
      console.log(recordset.recordsets[0][1]); 
    })
    })
  });

//add purchase order
router.post('/', (req, res, next) => {
    //logic to add record
    console.log(req.body.username);
    var conn = new sql.ConnectionPool(config);
    conn.connect().then((conn) => {
      var sqlreq = new sql.Request(conn);
      sqlreq.input('Username', sql.VarChar(30), req.body.username);
      sqlreq.input('Password', sql.VarChar(30), req.body.password);
      sqlreq.input('Email', sql.VarChar(30), req.body.email);
      sqlreq.input('Name', sql.VarChar(30), req.body.name);
      sqlreq.execute('saveuser').then(function(err, recordsets, returnValue, affected) {
        console.dir(recordsets);
        console.dir(err);
        conn.close();
      }).catch(function(err) {
            res.json({msg: 'Failed to add contact'});
            console.log(err);
      });
    });
  })

// delete purchase order
router.delete('/:id', (req, res, next) => {
    //logic to delete record
});

module.exports = router; 

如果仍然失败,请尝试仅使用 res.send() 而不是 res.json(),即使只是出于故障排除目的。

我建议的最后一件事是发送实际错误或至少某种类型的 4xx5xx 状态代码,以便 Angular HttpClient 可以将其视为实际错误,而不是成功的 HTTP 请求200 状态码。

希望对您有所帮助!

【讨论】:

    【解决方案2】:

    contact 变量添加安全导航操作。

    <div class= "container">
      <p>Its Working here also</p>
        {{contact?.Empno}}
        {{contact?.Ename}}
    </div>
    

    相当于contact != null ? contact.Empno: null

    更新:

    另外,添加错误处理代码:

    ngOnInit() {
      this.contactService.getPurchase().subscribe(
        (data: Contact) => {
          this.contact = {...data};
        },
        error => {
          console.log("Error Occured: "+ error);
        }
      );
    }
    

    【讨论】:

    • 我添加了另一个
      ,现在我得到了错误:Message: "Http failure during parsing for http://localhost:3000/" name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: "http://localhost:3000/" 还有SyntaxError: Unexpected token H in JSON at position 0 at JSON.parse
    • @AviralGoyal 您的回复应采用正确的 JSON 格式。此外,您的变量名称和 JSON 响应变量名称应该匹配。 Contact 类中的 Empno 应与 JSON 响应中的 Empno 变量匹配(区分大小写)。
    • 从邮递员复制并粘贴到 .json 文件并指向该 URL 时的响应会给出结果。据我所知,因此区分大小写或正确的 JSON 不是问题。我已经提到了我的问题中的所有价值观。请告诉我是否可以为您提供更多信息,这可能有助于解决问题。
    • @AviralGoyal 将您的 configUrl1 更改为 http://localhost:3000/purchase
    • 那是我得到错误的时候。在另一种情况下,我在 .json 文件中引用来自服务器的相同输出,则会显示数据。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签