【发布时间】: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) => { console.log(data); }); }校验值是字符串还是变量@ThienHoang 它给了我与上面相同的错误。由于某种原因没有收到数据。