0

I created a Node.js application and also an Angular application. I need to get data from the database and also store data to the database. I'm having problems connecting my Express.js server to the Angular application.

File user.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from '../User';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BASE_URL } from '../const/config';
import { MONGO_EXPRESS_URL } from '../const/config';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  constructor(private http: HttpClient) {}

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(`${MONGO_EXPRESS_URL}/fetchdata`);
  }
}

File users.component.ts

import { Component, OnInit } from '@angular/core';
import { UserService } from 'src/app/services/user.service';
import { User } from '../../User';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
  users: User[] = [];

  constructor(private userService: UserService) {}

  ngOnInit(): void {
    this.userService.getUsers().subscribe((users) => (this.users = users));
  }
}

This error pops up when I run the Angular application:

Enter image description here

File server.js

app.use("/", router);

app.listen(port, function () {
  console.log("Server is running on Port: " + port);
});

router.route("/fetchdata").get(function (req, res) {
  users.find({}, function (err, result) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

2 Answers 2

1

The problem is the route: https://localhost:4000.

It would be http://localhost:4000 (http:// instead of https://).

1
  • What is the reason for it? Why doesn't it work with HTTPS? Is there a story behind it? Preferably, please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today). Nov 19, 2021 at 12:57
0

It should kind of look like this on your Node.js. You should set up the Express.js server like so:

constructor() {
  this.app = express()
}

Initialize{
    this.app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT');
      if('OPTIONS' === req.method){
        res.sendStatus(200);
      }
      else {
          next();
      }
    })

  this.app.use(RouterWebservices)

    this.app.listen(your.HttpPort, your.Ip, () => {
      console.log('Server now listening at ', your.HttpPort, 'IP ', your.Ip);
    })
}

Then you need to declare your variables in a router.webservice.ts file:

export const RouterWebservices = express.Router()

RouterWebservices.get('/fetchdata', FetchWebservice)

And write a FetchWebserivce where you simply answer the request with data.

1
  • hey man i added the /fetchdata route to the question if anything need to change please let me know. thanks Sep 12, 2021 at 1:41

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.