0

I'm learning to code and just ran into this issue with Angular 6 which I can't seem to solve.I can't print Node.js data . When i run the server.js file individually , i can get the output data. But when i try to access Node.js backend through Angular 6 ,can't get the output data.

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'));

when i tried to access Node.js data through Angular ,i get this error

zone.js:2969 GET http://localhost:4000/issues 0 ()

But when i try to access Node.js data through server side , i get the output results

while executing server.js file on port 4000

please help me to find a solution.
Thanks in advance

1 Answers1

0

See Content-Security-Policy. Add meta-tag to app index.html:

<meta http-equiv="Content-Security-Policy"
    content="default-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:4000" />

Enable CORS in routes:

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();
});
Lemix
  • 2,415
  • 1
  • 15
  • 16
  • adding meta-tag doesn't do any good, it made more errors , like `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.` and do you mean i need to enable CORS in routes in my server.js file? if that is what you mean, i have changed that too, still the same error – athul jithu Sep 12 '18 at 19:04
  • I am an absolute beginner in the mean stack application development so please specify the file name that i needed to change – athul jithu Sep 12 '18 at 19:12
  • Your app and api hosted on different ports. You need set up Content-Security-Policy and CORS. – Lemix Sep 12 '18 at 21:06
  • https://stackoverflow.com/questions/18642828/origin-http-localhost3000-is-not-allowed-by-access-control-allow-origin – Lemix Sep 12 '18 at 21:16
  • i have been learning angular and node.js from the below [link] (https://codingthesmartway.com/angular-6-mean-stack-crash-course-part-3-connecting-front-end-to-back-end/) and the git [link] (https://github.com/seeschweiler/mean-stack-angular-6-part-3) can you please look into this tutorial and find a solution – athul jithu Sep 13 '18 at 10:08
  • it works for me. `git clone https://github.com/seeschweiler/mean-stack-angular-6-part-3.git` `cd frontend` `npm install` `ng serve` `cd backend` `npm install` `npm run-script dev` Angular CLI: 6.0.8 and Node: 9.4.0 – Lemix Sep 13 '18 at 11:09
  • thank you for the info , i have got cleared the error . It was stupid , i forgot to load the server side script in the terminal , that's why i get an error , Any way thanks for your help @Lemix – athul jithu Sep 18 '18 at 10:58