1
votes

I am trying to create an Angular app that sends GET & POST requests to an express server using NodeJS.

When I serve the app, GET & POST requests are meant to be sent to my local server, but I'm getting an error in the console, this error is logged below.

Also, when I go to localhost:3000, the server is running.

Here is my component class:

import { Component, OnInit } from "@angular/core";
import { RootService } from "./root.service";

@Component({
  selector: "app-root",
  templateUrl: "./root.component.html",
  styleUrls: ["./root.component.css"]
})
export class RootComponent implements OnInit {
  constructor(private rootService: RootService) {}

  ngOnInit() {
    this.rootService.getAPIData().subscribe(
      response => {
        console.log("response from GET API is ", response);
      },
      error => {
        console.log("error is ", error);
      }
    );

    this.rootService.postAPIData().subscribe(
      response => {
        console.log("response from POST API is ", response);
      },
      error => {
        console.log("error during post is ", error);
      }
    );
  }
}

And here is root.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class RootService {

  constructor(private http: HttpClient) { }

  getAPIData(){
    return this.http.get('/api/getData')
  }

  postAPIData(){
return this.http.post('/api/postData', {'firstName' : 'Code', 'lastName' : 'Handbook'})
  }
}

Here is my server code:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

app.get('/', (req, res) => {
res.send('Welcome to Node API')
})

app.get('/getData', (req, res) => {
res.json({'message': 'Hello World'})
})

app.post('/postData', bodyParser.json(), (req, res) => {
res.json(req.body)
})

app.listen(3000, () => console.log('Example app listening on port 3000!'))

I also have this proxy.conf.json file:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "pathRewrite": {"^/api" : ""}
  }
}

When I serve my app, I get the following output to the console:

error is
Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/getData", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:4200/api/getData: 404 Not Found", error: "\n\n\n\nError\n\n\n

Cannot GET /api/getData
\n\n\n" } root.component.ts:18:8 error during post is
Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost:4200/api/postData", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:4200/api/postData: 404 Not Found", error: "\n\n\n\nError\n\n\n
Cannot POST /api/postData
\n\n\n" }

Can someone please help me with this error?

3

3 Answers

0
votes

I think you need to pass in the path to proxy.conf when you start the Angular app.

Ref: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

0
votes

Your config should look like:

{
  "/api": {
    "target": "http://localhost:3000",
    "pathRewrite": {
      "^/api": ""
    }
  }
}
0
votes

1. First make a file "proxy.config.json" on root directory and add these lines inside:

{
  "/api/*": {
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug"
  }
}

2. On "angular.json" under script put:

     "start": "ng serve --proxy-config proxy.config.json",

3. On terminal write "npm start"

  note: Don't write "ng serve" , it won't run proxy configuration file.