Node.js 角度节点JS:输出未定义,Can';t从服务器访问数据
我刚刚开始在Node和Angular中编程,我正在尝试运行一个简单的应用程序,其中我将后端(localhost:3000)连接到前端并显示数据。如果在发出get请求时从服务器接收到的数据放在一个.json文件中,并且我在同一个文件夹中访问它,那么将显示数据 但是如果我使用api的地址(http://localhost:3000/purchase)从中拾取数据的浏览器中出现未定义的错误。 这是它在浏览器中显示的错误:Node.js 角度节点JS:输出未定义,Can';t从服务器访问数据,node.js,angular,rxjs,Node.js,Angular,Rxjs,我刚刚开始在Node和Angular中编程,我正在尝试运行一个简单的应用程序,其中我将后端(localhost:3000)连接到前端并显示数据。如果在发出get请求时从服务器接收到的数据放在一个.json文件中,并且我在同一个文件夹中访问它,那么将显示数据 但是如果我使用api的地址(http://localhost:3000/purchase)从中拾取数据的浏览器中出现未定义的错误。 这是它在浏览器中显示的错误: ContactsComponent.html:2 ERROR TypeErro
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)
这是我的服务器()在邮递员上的输出:
{
"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;
}
这是服务的角度代码:
{
"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;
}
这是定义联系人结构的代码:
{
"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>
route.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)
})
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
}
在节点中添加参数后,输出如下:
{
"Empno": "113 ",
"Ename": "Mary ",
"Sal": "15220 ",
"Deptno": "DP "
}
将安全导航操作添加到
contact
变量
<div class= "container">
<p>Its Working here also</p>
{{contact?.Empno}}
{{contact?.Ename}}
</div>
该问题可能与使用
bodyParser
有关。它可能正在尝试解析已解析的JSON。基本上,在顶层添加解析器一次,然后将其从路由中删除。也可以使用json()而不是send()连接到。我遇到过这样的问题:如果数据有一个名为data的属性,它可能会导致json解析/stringify失败
尝试以下方法。在App.js
中重新引入行App.use(bodyParser.json())
,只需在顶级位置(如此条目文件)添加一次。另外,从该文件中从/login
发布路径中删除jsonParser
中间件:
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()
,即使只是为了排除故障
我建议的最后一件事是发送实际错误或至少某种类型的4xx
或5xx
状态代码,以便Angular HttpClient可以将其视为实际错误,而不是带有200
状态代码的成功HTTP请求
希望这有帮助 组件初始加载时,触点
未定义,这将导致未定义错误。使用异步管道或使用ngIf仅在contact实际加载时呈现div。我已经添加了另一个,现在我收到错误消息:消息:“在对http://localhost:3000/名称:“HttpErrorResponse”确定:错误状态:200状态文本:“确定”url:http://localhost:3000/“
请逐步复制,让我们试试:this.contactService.getPurchase().subscribe((数据)=>{console.log(数据);});}代码>且检查值为字符串或variable@ThienHoang它给了我和上面一样的错误。由于某些原因,无法接收数据。我添加了另一个,现在收到错误:消息:“在解析的过程中Http失败。”http://localhost:3000/名称:“HttpErrorResponse”确定:错误状态:200状态文本:“确定”url:http://localhost:3000/"
还有语法错误:JSON中位于JSON位置0处的意外标记H。解析@aviragoyal您的响应应采用正确的JSON格式。此外,变量名和JSON响应变量名应该匹配Empno
应与JSON响应中的Empno
变量匹配(区分大小写)。从postman复制并粘贴到.JSON文件中并指向该URL时的响应将给出结果。因此,据我所知,区分大小写或正确的JSON不是问题。我在问题中提到了所有的价值观。请告诉我是否可以提供更多信息,这可能有助于解决问题。@Aviragoyal将configUrl1
更改为http://localhost:3000/purchase
这就是我得到错误的时候。在另一种情况下,我在一个.json文件中引用来自服务器的相同输出,显示数据。