【问题标题】:Can't print Node.js data with Angular 6无法使用 Angular 6 打印 Node.js 数据
【发布时间】:2018-09-12 17:53:02
【问题描述】:

我正在学习编码,只是遇到了 Angular 6 的这个问题,我似乎无法解决。我无法打印 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

请帮助我找到解决方案。
提前致谢

【问题讨论】:

    标签: node.js angular6 http-error


    【解决方案1】:

    请参阅内容安全策略。 将元标记添加到应用 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();
    });
    

    【讨论】:

    • 添加元标记没有任何好处,它会产生更多错误,例如core.es5.js:149 Refused to load the font 'https://fonts.gstatic.com/s/materialicons/v41/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2' because it violates the following Content Security Policy directive: "default-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:4000". Note that 'font-src' was not explicitly set, so 'default-src' is used as a fallback.,您的意思是我需要在我的 server.js 文件中的路由中启用 CORS 吗?如果这就是你的意思,我也改了,还是一样的错误
    • 我是平均堆栈应用程序开发的绝对初学者,所以请指定我需要更改的文件名
    • 您的应用程序和 api 托管在不同的端口上。您需要设置 Content-Security-Policy 和 CORS。
    • 我一直在从下面的 [link] (codingthesmartway.com/…) 和 git [link] (github.com/seeschweiler/mean-stack-angular-6-part-3) 学习 angular 和 node.js,您能否查看本教程并找到解决方案
    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 2020-01-06
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多