Home > Enterprise >  Cant connect express server to the angular frontend
Cant connect express server to the angular frontend

Time:09-16

I created a nodejs app and also an Angular app I need to get data from db and also store data to db. I'm having problems connecting my express server to the angular app.

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`);
  }
}

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 app

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

CodePudding user response:

can you share where you set up the route /fetchdata on your express server?

It should kinda look like this on your nodeJS you should set up the express 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

export const RouterWebservices = express.Router()

RouterWebservices.get('/fetchdata', FetchWebservice)

and write a FetchWebserivce where you simply answer the request with data

CodePudding user response:

The problem is the route: https://localhost:4000. It would be http://localhost:4000 (http:// instaed of https:// )

  • Related