无法使用 Angular 6 打印 Node.js 数据
Can't print Node.js data with Angular 6
我正在学习编码,只是 运行 使用 Angular 6 我似乎无法 solve.I 无法打印 Node.js 数据.当我 运行 单独 server.js 文件时,我可以获得输出数据。但是当我尝试通过 Angular 6 访问 Node.js 后端时,无法获取输出数据。
issue.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class IssueService {
uri = 'http://localhost:4000';
constructor(private http: HttpClient) { }
getIssues() {
return this.http.get(`${this.uri}/issues`);
}
getIssueById(id) {
return this.http.get(`${this.uri}/issues/${id}`);
}
addIssue(title, responsible, description, severity) {
const issue = {
title: title,
responsible: responsible,
description: description,
severity: severity
};
return this.http.post(`${this.uri}/issues/add`, issue);
}
updateIssue(id, title, responsible, description, severity, status) {
const issue = {
title: title,
responsible: responsible,
description: description,
severity: severity,
status: status
};
return this.http.post(`${this.uri}/issues/update/${id}`, issue);
}
deleteIssue(id) {
return this.http.get(`${this.uri}/issues/delete/${id}`);
}
}
list.component.ts
import { Component, OnInit } from '@angular/core';
import { IssueService } from '../../issue.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
constructor(private issueService: IssueService) { }
ngOnInit() {
this.issueService.getIssues().subscribe((issues) => {
console.log(issues);
});
}
}
server.js
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import Issue from './models/Issue';
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/issues');
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
router.route('/issues').get((req, res) => {
Issue.find((err, issues) => {
if (err)
console.log(err);
else
res.json(issues);
});
});
router.route('/issues/:id').get((req, res) => {
Issue.findById(req.params.id, (err, issue) => {
if (err)
console.log(err);
else
res.json(issue);
});
});
router.route('/issues/add').post((req, res) => {
let issue = new Issue(req.body);
issue.save()
.then(issue => {
res.status(200).json({'issue': 'Added successfully'});
})
.catch(err => {
res.status(400).send('Failed to create new record');
});
});
router.route('/issues/update/:id').post((req, res) => {
Issue.findById(req.params.id, (err, issue) => {
if (!issue)
return next(new Error('Could not load document'));
else {
issue.title = req.body.title;
issue.responsible = req.body.responsible;
issue.description = req.body.description;
issue.severity = req.body.severity;
issue.status = req.body.status;
issue.save().then(issue => {
res.json('Update done');
}).catch(err => {
res.status(400).send('Update failed');
});
}
});
});
router.route('/issues/delete/:id').get((req, res) => {
Issue.findByIdAndRemove({_id: req.params.id}, (err, issue) => {
if (err)
res.json(err);
else
res.json('Remove successfully');
})
})
app.use('/', router);
app.listen(4000, () => console.log('Express server running on port 4000'));
当我尝试通过 Angular 访问 Node.js 数据时,出现此错误
zone.js:2969 GET http://localhost:4000/issues 0 ()
但是当我尝试通过服务器端访问 Node.js 数据时,我得到了输出结果
while executing server.js file on port 4000
请帮我找到解决办法。
提前致谢
参见内容安全策略。
为应用程序添加元标记 index.html:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:4000" />
在路由中启用 CORS:
app.use('/*', function (req, res, next) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, X-App-Version');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PATCH');
next();
});
我正在学习编码,只是 运行 使用 Angular 6 我似乎无法 solve.I 无法打印 Node.js 数据.当我 运行 单独 server.js 文件时,我可以获得输出数据。但是当我尝试通过 Angular 6 访问 Node.js 后端时,无法获取输出数据。
issue.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class IssueService {
uri = 'http://localhost:4000';
constructor(private http: HttpClient) { }
getIssues() {
return this.http.get(`${this.uri}/issues`);
}
getIssueById(id) {
return this.http.get(`${this.uri}/issues/${id}`);
}
addIssue(title, responsible, description, severity) {
const issue = {
title: title,
responsible: responsible,
description: description,
severity: severity
};
return this.http.post(`${this.uri}/issues/add`, issue);
}
updateIssue(id, title, responsible, description, severity, status) {
const issue = {
title: title,
responsible: responsible,
description: description,
severity: severity,
status: status
};
return this.http.post(`${this.uri}/issues/update/${id}`, issue);
}
deleteIssue(id) {
return this.http.get(`${this.uri}/issues/delete/${id}`);
}
}
list.component.ts
import { Component, OnInit } from '@angular/core';
import { IssueService } from '../../issue.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
constructor(private issueService: IssueService) { }
ngOnInit() {
this.issueService.getIssues().subscribe((issues) => {
console.log(issues);
});
}
}
server.js
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import Issue from './models/Issue';
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://localhost:27017/issues');
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
router.route('/issues').get((req, res) => {
Issue.find((err, issues) => {
if (err)
console.log(err);
else
res.json(issues);
});
});
router.route('/issues/:id').get((req, res) => {
Issue.findById(req.params.id, (err, issue) => {
if (err)
console.log(err);
else
res.json(issue);
});
});
router.route('/issues/add').post((req, res) => {
let issue = new Issue(req.body);
issue.save()
.then(issue => {
res.status(200).json({'issue': 'Added successfully'});
})
.catch(err => {
res.status(400).send('Failed to create new record');
});
});
router.route('/issues/update/:id').post((req, res) => {
Issue.findById(req.params.id, (err, issue) => {
if (!issue)
return next(new Error('Could not load document'));
else {
issue.title = req.body.title;
issue.responsible = req.body.responsible;
issue.description = req.body.description;
issue.severity = req.body.severity;
issue.status = req.body.status;
issue.save().then(issue => {
res.json('Update done');
}).catch(err => {
res.status(400).send('Update failed');
});
}
});
});
router.route('/issues/delete/:id').get((req, res) => {
Issue.findByIdAndRemove({_id: req.params.id}, (err, issue) => {
if (err)
res.json(err);
else
res.json('Remove successfully');
})
})
app.use('/', router);
app.listen(4000, () => console.log('Express server running on port 4000'));
当我尝试通过 Angular 访问 Node.js 数据时,出现此错误
zone.js:2969 GET http://localhost:4000/issues 0 ()
但是当我尝试通过服务器端访问 Node.js 数据时,我得到了输出结果
while executing server.js file on port 4000
请帮我找到解决办法。
提前致谢
参见内容安全策略。 为应用程序添加元标记 index.html:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:4000" />
在路由中启用 CORS:
app.use('/*', function (req, res, next) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, X-App-Version');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PATCH');
next();
});