Initiating a post request to the express server

My service includes a function that retrieves the user's current location using latitude and longitude coordinates. I am attempting to send this information to my server in order to incorporate it into a query. However, my post request does not appear to be functioning correctly. Below is an excerpt from my appInitializer module demonstrating how this function is invoked.

eventServer.js

router.get('/ticketmaster-events', (req, res) => {
/*   including it in this query */
  axios.get('http://app.ticketmaster.com/discovery/v2/events.json?apikey=hneV7jzq6Uz7IyQC7GtEHz5s2nTsU6Jm&size=200')
  .then(res2 => {
    res.send(res2.data._embedded.events)
  })
  .catch(err => res.send(err))
  });

router.route('/currentLatLong').post((req, res, next) => {
  console.log("hello this test")
  try{
    res.end("response is " + req.body);
    console.log(req);
  }
  catch(err) {
    res.send(err);
  }
});

google.service.ts

export class GoogleService {
  uri = 'http://localhost:4000';
  public currentLat: number;
  public currentLng: number;
  public currentLatLong: any = [];

    getUserLocation() {
    /* locating the User */
    if (navigator.geolocation) {
        console.log('good');
        navigator.geolocation.getCurrentPosition(position => {
        this.currentLat = position.coords.latitude;
        this.currentLng = position.coords.longitude;
        this.data.latitudeSource.next(this.currentLat);
        this.data.longitudeSource.next(this.currentLng);
        const currentLatLong = {
          latitude : this.currentLat,
          longitude: this.currentLng
        };
        console.log(currentLatLong);

        return this.http.post(`${this.uri}/currentLatLong`, JSON.stringify(currentLatLong)).subscribe(response => {
          console.log('your response is here', JSON.stringify(response));
           },
           error => {
             console.log('error occured', error);
          });
      });
    } else {
      console.log('bad');
    }
  }
  constructor(private data: DataService, private http: HttpClient) { }
}

appInitializer.module.ts

import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { TicketMasterService } from '../../services/tmService/ticket-master.service';
import { GoogleService } from '../../services/googleService/google.service';

    export function fetchTmData(tmService: TicketMasterService) {
  return () => tmService.fetchTmData();
}

    export function getUserLocation(googleService: GoogleService) {
  return () => googleService.getUserLocation();
}

    @NgModule({
    imports: [HttpClientModule],
    providers: [
    TicketMasterService,
    GoogleService,
    { provide: APP_INITIALIZER, useFactory: fetchTmData, deps: [TicketMasterService], multi: true },
    { provide: APP_INITIALIZER, useFactory: getUserLocation, deps:[GoogleService], multi: true }
    ]
    })
    export class AppLoadModule { }

Answer №1

It's unclear what specific error you're encountering, but modifying your GoogleService service as shown below may help.

export class GoogleService {
  uri = 'http://localhost:4000';
  public currentLat: number;
  public currentLng: number;
  public currentLatLong: any = [];

  getUserLocation() {
    /* Locate the User */
    if (navigator.geolocation) {
        console.log('good');
        navigator.geolocation.getCurrentPosition(position => {
        this.currentLat = position.coords.latitude;
        this.currentLng = position.coords.longitude;
        this.data.latitudeSource.next(this.currentLat);
        this.data.longitudeSource.next(this.currentLng);
        this.currentLatLong[0] = this.currentLat;
        this.currentLatLong[1] = this.currentLng;

       this.http.post(`${this.uri}/currentLatLong`, JSON.stringify(this.currentLatLong), {
          headers: new HttpHeaders({'Content-Type': 'application-json'})}
          ).subscribe(response=>{
           consol.log("your response is here")
           },
           error=>{console.log("error occoured")});

      });
    }
  }
  constructor(private data: DataService, private http: HttpClient) { }
}

To resolve the issue, ensure your http requests are handled as Observable, and convert your object to a string as demonstrated in the solution above.

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

Child component not inheriting Angular Material styles

I am experiencing an issue with the default styles of Angular Material. I have a parent dashboard component with child components named "HomeComponent" and "RegistrationComponent". The Input box and button from Angular Material work properly on the dashboa ...

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Upon clicking the button, the Angular Mat-Table with Reactive Forms fails to display any data, instead adding a blank row accompanied by errors

When the AddRow_click() function is executed, I populate the insuranceFormArray and assign its values to the datasource. However, after adding an entry, an empty row appears in the table, and error messages are displayed in the console. Only a subset of th ...

Angular material stepper displaying incorrectly

Here is the HTML code I used for creating an Angular Material stepper: <mat-horizontal-stepper class="stepper"> <mat-step label="Basic" state="cloud_download"> Step 1 <button mat-button matSteppe ...

Encountering a cross-origin resource sharing (CORS) error while attempting

My Vue App is being hosted on an express server (nodejs running on port 60702) with the following setup: 'use strict'; const fs = require('fs'); const path = require('path'); const express = require('express'); var h ...

Issue encountered during the creation of a new Angular application (npm ERROR! 404 Not Found: @angular/animations@~7.1.0.)

I am currently using Windows 10, Node v11.0.0, and Angular CLI: 7.1.4. I encountered an error when trying to create a new Angular application. The error message is npm ERR! code E404 npm ERR! 404 Not Found: @angular/animations@~7.1.0. Error stack: 0 info ...

Why is the function app.get('/') not triggering? The problem seems to be related to cookies and user authentication

Need help with app.get('/') not being called I am working on implementing cookies to allow multiple users to be logged in simultaneously. Currently, users can log in successfully. However, upon refreshing the page, all users get logged in as the ...

Error encountered when initializing OGM on Neo4j GraphQL Express Server due to unhandled promise rejection

Currently, I am integrating Express with Neo4j GraphQL. An exception has been thrown without specific line indications in my code. node:internal/process/promises:289 triggerUncaughtException(err, true /* fromPromise */); ^ [Unhand ...

Sanitizing form fields in node.js: Best practices and techniques

I recently installed the express-validator package to help me sanitize form fields. However, when I tried using it, I encountered an error: TypeError: req.sanitize is not a function. var express = require('express'); var router = express.Router() ...

Optimizing Angular for search engines: step-by-step guide

Regarding Angular SEO, I have a question about setting meta tags in the constructors of .ts files. I have implemented the following code: //To set the page title this.titleServ.setTitle("PAGE TITLE") //To set the meta description this.meta.addTag ...

Angular component linked to a dynamic object requiring user confirmation before changing or reverting to the original value

I've been working on getting a simple <select> behavior where the value reverts back if the user cancels the change. I managed to achieve it, but it took me quite a few hours and I'm not entirely satisfied with the implementation as it&apos ...

Guide on how to add an array of objects in Mongoose using ExpressJS

I am looking to add a product with various sizes and prices but I'm experiencing an issue with storing this array of objects in MongoDB. Below is my Product Schema: const productSchema = new mongoose.Schema({ product_name: {type:String, required: ...

During the transpiling process, the metadata of an Angular component may become lost

Encountering another error: Uncaught Error: Unexpected value 'UserDialogComponent' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation. Current behavior Summary: When incorporating an external libra ...

Angular 5 - Keeping track of variable updates

I've searched various topics on this issue, but none seem to address my specific problem. I need a way to detect changes in the properties of a component without having to convert the variable into an array or iterable. I tried using Subject, but coul ...

How can a response header be included for a redirect in Express?

In my NodeJS Express application, I am attempting to redirect users to a different URL and then include a specific header in the response. Is it feasible to achieve this functionality? For instance, let's say a request is redirected to https://example ...

What is the best way to divide percentages accurately in Angular?

I am currently working on splitting percentages dynamically with Angular. For example, if txtBox1 has 75%, I want to split the remaining 25% between txt2 and txt3. If I change txt1 to 50%, then I want txt2 and txt3 each to receive 25%. The values may vary, ...

How to Implement Modal Popups on Click in Angular with the AmCharts XY Chart

Our goal is to display a modal window when users click on a data point. The current code we are using is as follows: constructor(public dataservice: DataserviceService, private modalService: NgbModal, private router: Router) { } ... ... bullet.events.on( ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

Issue with setting a cookie on a separate domain using Express and React

My backend is hosted on a server, such as backend.vercel.app, and my frontend is on another server, like frontend.vercel.app. When a user makes a request to the /login route, I set the cookie using the following code: const setCookie = (req, res, token) = ...

Comparing app.get() and api.get()/Router.get() methods in ExpressJS

Although I have a basic understanding of this concept, I still believe there is more to learn. Currently, my comprehension includes the fact that app.get() and app.post() are mainly used for making AJAX calls to the server, while Routes are intended for cr ...