Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js:

app.get('/post', (req,res) =>{
  let data =
  [{
    userId: 10,
    id: 98,
    title: 'laboriosam dolor voluptates',
    body: 'doloremque ex facilis sit sint culpa{ userId: 10'
    },
    {
    id: 99,
    title: 'temporibus sit alias delectus eligendi possimus magni',
    body: 'quo deleniti praesentium dicta non quod'
  }];

  res.status(200).json(data);

});

The content of my my.service.ts file can be seen below:

export class MyService {

  constructor(private http: HttpClient) { }

    fetchData(): any {
        console.log('reaches');
        return this.http.get('/post').pipe(
          map((post) => {
            console.log(post.json());
            return post.json();
          })
        );
      }
}

Also, here is a snippet from my sem.component.ts:

export class SemComponent implements OnInit {
  posts: any = [];

  constructor(private myService: MyService) { }

  ngOnInit() {
    console.log('reaches');
    this.myService.fetchData().subscribe(posts => {
      this.posts = posts;
      console.log(posts);
    });
  }
}

In addition, I have defined my routes in the Routes file as follows:

export const myRoutes: Routes = [
  {
    path: 'post',
    component: SemComponent
  }]

This is how I retrieve JSON data in Angular.

However, when I navigate to the URL 'localhost:3000/post', it does not reach the service.ts code directly displaying the JSON data from the app.js file instead.

https://i.stack.imgur.com/p7890.png

Answer №1

class DataRetrievalService {
  constructor(private http: HttpClient) { }
    fetchInformation(): Promise<any> {
      return this.http
      .get("url").toPromise()
      .then((response)=>{
        return response;
      })
      .catch((error)=>{
        console.log(error)
      })
  }
}

When using the SemComponent, you can access the retrieved data like this:

class ExampleComponent implements OnInit {
dataList: any = [];
constructor(private dataRetrievalService: DataRetrievalService) { }
    ngOnInit() {
        console.log('reaches');
        this.dataRetrievalService.fetchInformation().then(data => {
          this.dataList = data;
          console.log(this.dataList);
        });
    }
}

Answer №2

Running both your web server (app.js) and angular application on the same port and context is causing an issue. To resolve this, consider changing either the port number or the context ('/post').

A collision has occurred, with both the router path and app.js request context set to 'post'.

Please verify and adjust the port and context settings for your applications, as this should alleviate the problem.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the error within a promise be captured when using resolve()?

Check out the code snippet below: userUpdate(req: Request, res: Response) { this.userTaskObj.userUpdate(req.params.id, req.body).then(() => { res.status(200).json({ status: 'OK', message: 'User updated', ...

Can a Typescript type alias be altered in real time?

Currently, I am developing an Angular library that will function as an API client. The challenge I am facing is that some of the applications utilizing this library are configured with an HttpInterceptor to automatically transform date strings into JavaScr ...

Assign a class to an Angular component's host element without any conditions

In my Angular project, I have a component where I need to apply a class unconditionally. To achieve this, the host property within the @Component decorator can be used: import { Component } from '@angular/core'; @Component({ selector: 'ap ...

After changing routes in Angular 4, the application experiences decreased speed and a continual increase in the number of nodes, particularly noticeable in Chrome but not in Firefox

After switching routes multiple times, I noticed a decrease in the app's speed. Upon inspecting the 'performance + memory' section using Chrome debugger, I observed an increasing number of DOM nodes. It seems that the DOM nodes are not prop ...

AngularJS - Not binding $scope to the DOM

Recently starting out with Angular, I decided to practice by creating a simple website. One of the features I want to include is displaying the number of times a button has been clicked through data binding. Here's the controller code I've writte ...

How can I create a dynamic height for a scrollable div?

How can I build a section with a defined height that contains a sticky header (with a dynamic height) and a scrollable body? I want the body to be scrollable, but due to the header's changing height, I'm unable to set an exact height. What should ...

Leveraging the capabilities of Express functions on the client side through the require method in Node.js

Trying to access the configuration variables set in the file named test.js which contains -- var aws = require('aws-sdk'); exports.connect = function(){ return aws; } Now, I am attempting to access it upon an OnClick event taking place ...

Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout. <html data-ng-app="app"> . . . //menu section <li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat"> ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

Discover the Power of Node.js with the @aws-sdk/client-s3 Package, Leveraging AWS CLI Credentials Stored in

A Nodejs project has been set up with media files stored in an S3 Bucket and utilizing the @aws-sdk/client-s3 as the AWS SDK Client. The project consists of two important files, namely .env and S3Bucket.js. The content of .env (located in the root directo ...

Display options based on the value selected in the preceding selection

How can I dynamically display select options in an Angular select based on a previously selected value? Take a look at the code snippet below. Here, I have implemented a conditional display of select options (Target 1/Target 2) based on the value selected ...

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

Angular Universal in combination with AngularFire server experiences a hanging issue due to the first() pipe

I am currently developing an angular/firestore application that requires SSR capabilities. I have integrated angular universal into the project and everything seems to be functioning properly until I utilize the first() pipe on any of the firestore calls, ...

Error in Node: resolve-url-loader - CSS resolution error

Trying to set up a React project as the development server on my Surface has been causing issues, unlike when I run the same configuration on my PC. Despite trying to replicate the same conditions, the problem persists. The error message received is: ./s ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

Collaborating with Ladda button functionality

I have a button with ladda functionality, shown below. <button class="btn btn-primary btn-xs ladda-button" data-style="slide-left" data-size="xs" v-on:click="refreshPage()">Refresh</button> The onClick event is triggered by VueJs. When the b ...

I am having trouble loading the component; please direct me to the login page

Utilizing Angular 7 to develop an admin dashboard, I encountered an issue with the home page. The home page is supposed to load before logging in, but it only works after logging in. Prior to logging in, the page briefly appears for a second and then autom ...

Upon employing the setTimeout method, the element with the id "sign-in-block" will have its display style set to "none" after a delay of 1000 milliseconds

I incorporated the setTimeout() function to make the HTML component appear for 1 second upon pageload. However, I would prefer this component not to load at all. Should I set the delay in the setTimeout() function to 0ms? Alternatively, is there another ...

The issue with the full postback in the updatepanel is triggered by utilizing JavaScript on the button's onclick event within

During my testing, I encountered an issue with buttons inside a repeater within an update panel. When adding asyncpostback triggers for the buttons using <Trigger></Trigger>, an error is generated indicating that the button could not be found. ...

What could be causing this JavaScript if statement to malfunction?

I found myself with some free time and decided to create a basic API using JavaScript. What I thought would be simple turned into a frustrating mistake. Oddly enough, my if/else statement isn't working correctly - it only executes the code within the ...