javascriptnode.jsangulartypescriptaxios

How to send data from angular app components to index.js(node server)


I ‍have‍ trie‍d‍ many t‍i‍mes but I don't k‍n‍o‍w how t‍o s‍end variables to the server

I have t‍h‍e‍se 3 variables inside angular components app.component.ts

-

import { Component, OnInit } from '@angular/core';
import { DataService } from 'src/app/services/data.service';
import { ChartDataSets, ChartOptions, ChartType } from 'chart.js';
import { Color, Label } from 'ng2-charts';
import {
  HttpHeaders,
  HttpParams,
  HttpClientModule,
  HttpClient,
} from '@angular/common/http';

@Component({
  selector: 'app-linechart',
  templateUrl: './linechart.component.html',
  styleUrls: ['./linechart.component.scss'],
})
export class LinechartComponent implements OnInit {
  public lineChartOptions: ChartOptions = {
    responsive: true,
    maintainAspectRatio: true,
    title: {
      display: true,
      position: 'left',
      text: 'worldwide Covid 19 Case Summary',
    },
    legend: {
      position: 'top',
      align: 'start',
    },
    // We use these empty structures as placeholders for dynamic theming.
    scales: {
      xAxes: [
        {
          ticks: {
            autoSkip: true,
            //max:500
            maxRotation: 0,
            minRotation: 0,
          },
        },
      ],

      yAxes: [{}],
    },
  };
  public lineChartLabels: Label[] = [
    '2006',
    '2007',
    '2008',
    '2009',
    '2010',
    '2011',
    '2012',
  ];

  public lineChartType: ChartType = 'line';

  public lineChartLegend = true;

  public lineChartData: ChartDataSets[] = [
    { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
    { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' },
  ];

  countries: any;
  countryCode: any;
  startDate: any;
  endDate: any;

  constructor(private oip: DataService, private http: HttpClient) {}

  ngOnInit() {
    this.oip.getCountries().subscribe((data) => {
      this.countries = data;
      console.log(this.countries);
    });
  }

  getCoronaDataRange(txtSD: any, txtED: any) {
    this.startDate = txtSD.value;
    this.endDate = txtED.value;
    console.log(this.startDate);
    console.log(this.endDate);


  }

  getCountryCode(countryCode: any) {
    this.countryCode = countryCode;
    console.log(this.countryCode);
  }
}

I want to pass them to inside the parameters of my server index.js instead of params: { startDate:'2019-01-05', endDate:'2020-09-21', countryCode:'MY' }

const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const http = require('http');
const server = http.createServer(app);
const port = 4600;

var corsOptions = {
    origin: ["http://localhost:4200","http://localhost:4000"]
}

app.use(cors(corsOptions));

app.get('/', (req, res) => {
    res.status(200).send('starting server');
})

app.get('/corona-data', (req, res) => {

    axios({
        method: 'GET',
        baseURL: 'https://api.oip.tmrnd.com.my',
        url: 'app/t/opendata.oip.tm.com.my/coronatracker/1.0.0/country',
        params: {
            startDate:'2019-01-05',
            endDate:'2020-09-21',
            countryCode:'MY'
        },
        headers: {
            Authorization : 'Bearer 0e9ceb08-9a2c-3311-999e-59a2989deb3f'
        }
    }).then((result) => {
        console.log(result.data);
        res.status(200).json(result.data);

    }).catch(error => {
        console.error('Error Has Occured');
        console.log(error);
        res.status(500).json(error.message);
    });
});

// Start the service
server.listen(port, () => {
    console.log('Server is listening to port ' + port);
})

Solution

  • You can use HttpClientModule which is inbuilt angular. Add it to your app.module.ts imports array. Feel free to add the HTTP post request to be called in ngOnInit (wrapping it in a method) with request data.

    Then update your component like below to send startdate and enddate:

    import { Component, OnInit } from '@angular/core';
    import { DataService } from 'src/app/services/data.service';
    import { ChartDataSets, ChartOptions, ChartType } from 'chart.js';
    import { Color, Label } from 'ng2-charts';
    import { HttpClient } from '@angular/common/http';
    
    @Component({
      selector: 'app-linechart',
      templateUrl: './linechart.component.html',
      styleUrls: ['./linechart.component.scss'],
    })
    export class LinechartComponent implements OnInit {
      public lineChartOptions: ChartOptions = {
        responsive: true,
        maintainAspectRatio: true,
        title: {
          display: true,
          position: 'left',
          text: 'worldwide Covid 19 Case Summary',
        },
        legend: {
          position: 'top',
          align: 'start',
        },
        scales: {
          xAxes: [
            {
              ticks: {
                autoSkip: true,
                maxRotation: 0,
                minRotation: 0,
              },
            },
          ],
          yAxes: [{}],
        },
      };
      public lineChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
      public lineChartType: ChartType = 'line';
      public lineChartLegend = true;
      public lineChartData: ChartDataSets[] = [
        { data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
        { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' },
      ];
      countries: any;
      countryCode: any;
      startDate: any;
      endDate: any;
    
      constructor(private dataService: DataService, private http: HttpClient) {}
    
      ngOnInit() {
        this.dataService.getCountries().subscribe((data) => {
          this.countries = data;
          console.log(this.countries);
        });
      }
    
      getCoronaDataRange(txtSD: any, txtED: any) {
        this.startDate = txtSD.value;
        this.endDate = txtED.value;
        console.log(this.startDate);
        console.log(this.endDate);
    
        
        const requestData = { 
          startDate: this.startDate, // set start date
          endDate: this.endDate, // set end date
          countryCode: this.countryCode, // set country code
        };
    
        
        this.http.post<any>('http://localhost:4600/corona-data', requestData) // using http-client In angular send post request to node server
          .subscribe((response) => {
            console.log('Server response:', JSON.stringify(response));
          }, (error) => {
            console.error('Error sending data to server:', error);    
          });
      }
    
      getCountryCode(countryCode: any) {
        this.countryCode = countryCode;
        console.log(this.countryCode);
      }
    }
    

    Then update the node server to receive the post request like below:

    const express = require('express');
    const axios = require('axios');
    const cors = require('cors');
    const app = express();
    const http = require('http');
    const server = http.createServer(app);
    const port = 4600;
    
    app.use(cors());
    
    app.use(express.json());
    
    app.get('/', (req, res) => {
      res.status(200).send('Starting server');
    });
    
    app.post('/corona-data', (req, res) => {
      const { startDate, endDate, countryCode } = req.body;
    
      axios({
        method: 'GET',
        baseURL: 'https://api.oip.tmrnd.com.my',
        url: 'app/t/opendata.oip.tm.com.my/coronatracker/1.0.0/country',
        params: {
          startDate,
          endDate,
          countryCode,
        },
        headers: {
          Authorization: 'Bearer 0e9ceb08-9a2c-3311-999e-59a2989deb3f',
        },
      })
        .then((result) => {
          console.log(result.data);
          res.status(200).json(result.data);
        })
        .catch((error) => {
          console.error('Error Has Occured');
          console.log(error);
          res.status(500).json(error.message);
        });
    });
    
    server.listen(port, () => {
      console.log('Server is listening to port ' + port);
    });