An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js.

Below is the HTML code snippet:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  </head>
  <body>
      latitude: <span id="latitude"></span>&deg;<br />
      longitude: <span id="longitude"></span>&deg;<br />
    </p>
    <button id="geolocate">geolocate</button>
    <script src="main.js"></script>
  </body>
</html>

Here's a part of my main.js file:

document.getElementById('geolocate').addEventListener('click', event => { 

    if ('geolocation' in navigator) { 
        console.log('Geolocation available');
        navigator.geolocation.getCurrentPosition(position => {                    
            var X = position.coords.latitude;   
            var Y = position.coords.longitude;
            console.log(X, Y);
            document.getElementById('latitude').textContent = X;
            document.getElementById('longitude').textContent = Y;
            
             const data = {X, Y}
             const options = {
                method: 'POST',
                body: JSON.stringify(data),
                headers: {
                    'content-type': 'application/json'
                 }
             }
        fetch('/api', options);
      });
}  else {  
        console.log('Geolocation not available');
      }
}); 

And here's the Node.js code snippet:

const express = require('express');
const app = express();
app.listen(3000, () => console.log('Listening at 3000'));

app.post('/api', (req, res) => {
  console.log(req);
});

When I run this, I keep getting a 404 error. Any idea what I might be doing wrong? Any advice would be appreciated.

EDIT:

This app works fine on my VPS. I also have SSL aliases for my domain. I use nodemon to run Node.js as a process. Here are the logs:

user_name_with_sudo  11451  0.5  3.6 663672 38152 pts/0    Sl+  11:05   0:00 node /bin/nodemon index.js $

As you can see, it's running as a process.

httpd service status - Oct 20 17:14:21 www.{my domain}.pl systemd[1]: Started The Apache HTTP Server. 

Working on CentOS7.

Answer №1

Make sure to include the full path for the fetch. You are connecting to a server at localhost on port 3000

main.js:

document.getElementById('geolocate').addEventListener('click', event => { 

if ('geolocation' in navigator) { 
    console.log('geolocation available');
    navigator.geolocation.getCurrentPosition(position => {                    
        var x = position.coords.latitude;   
        var y = position.coords.longitude;
        console.log(x, y);
        document.getElementById('latitude').textContent = x;
        document.getElementById('longitude').textContent = y;
        
         const data = {x, y}
         const options = {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'content-type': 'application/json'
             }
         }
    fetch('http://localhost:3000/api', options)
        .then(response => response.json())
        .then(data => {
            // if everything is ok, it should log the object message: "Long lang sent to express" from the server
            console.log(data)
        });
  });
...

The server-side code will look like this

const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at 3000'));

app.post('/api', (req, res) => {
  try {
      const {x, y} = req.body
      console.log(x, y)
      res.status(200).json({ message: "Long lang sent to express" })
   } catch (e) {
       res.status(500).json({ message: 'Something went wrong, please try again' })
   }
});

Try using lowercase variables (example: not using X, Y.. but using x, y) if they are not constants :) Good luck with programming

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

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

A guide to setting a custom icon for the DatePicker component in Material-UI 5

Seeking to incorporate custom Icons from react-feathers, I have implemented a CustomIcon component which returns the desired icon based on the name prop. Below is the code for this component. import React from 'react'; import * as Icon from &apo ...

The HTML embed element is utilized to display multimedia content within a webpage, encompassing

Currently, I am working on a static website for my Computer Networks course. Students need to be able to download homework files in PDF format from the website. I have used embed tags to display the files online, but I'm facing an issue where the embe ...

Using PHP and JQuery to send two variables via the post method

I've been attempting to send two variables from two input fields using jQuery to a PHP page, but I'm having trouble retrieving the data. It seems to work fine when I only have one variable, but as soon as I try with two, it doesn't seem to w ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

Execute Laravel Mix without the need for a system-wide installation of Node.js and npm

Currently working on a Laravel project that requires building styles and scripts using laravel-mix. However, the testing server (Ubuntu 20.04.4) does not have Node globally installed. Node and npm are located in separate folders within the system, so I hav ...

An odd issue has arisen where the website functions properly in Firefox 3.0 but encounters problems when accessed in Firefox 3

Could someone investigate this issue for me? When you click on the showcase and then on the logo, a modal window should open with the logo. It works perfectly in FF 3.0, but in FF 3.5, the tab switches from showcase to home after clicking the logo. Even ...

This error message occurs when trying to access JSON keys from an object with an invalid operand in the 'in' operation

Check out the fiddle I created here: http://jsfiddle.net/kc11/h6nh1gvw/2/ I'm attempting to extract keys from a JSON string using this code: var keys = $.map(a, function(element,key) { return key; }); . But unfortunately, I keep encountering the er ...

Altering styles of a child component within a parent component using material-ui

I am trying to customize the appearance of a child component from within the parent component Let's take a look at the child component, MyButton.js: import ButtonComponent from '@material-ui/core/Button' const useStyles = makeStyle((theme) ...

Updating parent data when new data is added in child component in React

I'm just starting to learn React and I've been reading a lot about updating children components when the parent component is updated, but I haven't come across much information about the opposite scenario. Currently, I have a parent compone ...

Mysterious and never-ending loop that seems to loop endlessly and eludes my

My prototype includes a method for adding callbacks: /* * Add a callback function that is invoked on every element submitted and must return a data object. * May be used as well for transmitting static data. * * The callback function is supposed to e ...

Experiencing a problem when attempting to submit a post request on a React application connected to

Could you assist me in resolving the following issue? I am encountering an error when attempting to add a user to the database, showing: "Error:MongoError: E11000 duplicate key error collection: test.users index: username_1 dup key: { : null }" Below is t ...

Problems arise with identification of asynchronous functions

My async functions have been used successfully in various projects, but when incorporating them into a new project, they suddenly stopped working. One of the functions causing trouble is: const ddbGet = async (params) => { try { const data ...

Having difficulty incorporating multiple "if" statements into my code

I'm currently working on creating an IE9 specific if statement. Basically, I want to check if the menu is collapsed and then move 3 classes from the left if it is true, or in the opposite direction if it is false. However, I'm struggling to get t ...

Siblings are equipped with the advanced selector feature to

I'm struggling to understand this setup I have: <div class="container"> for n = 0 to ... <a href="some url">Link n</a> endfor for each link in ".container" <div class="poptip"></div> ...

Running Node.js on Ubuntu using Nginx proves to be a challenging task

I have developed a basic server utility using Node.js, Express, and EJS that runs smoothly on my Windows computer. After transferring the updates to an Ubuntu server and launching them with node index.js, everything continued to work fine. This is an exc ...

The npm encountered an error with code ENOENT and an error number of 34

Here is my initial script setup for a React project. "scripts": { "prestart": "babel-node tools/startMessage.js", "start": "npm-run-all --parallel test:watch open:src lint:watch", "open:src": "babel-node tools/srcServer.js", "lint": "node_ ...

In mongoose schema, number types are always stored as strings

My schema is simple, with the contact field defined as a Number data type. However, I noticed that the input data for contact always gets saved as a string in MongoDB. I'm unsure of what's happening behind the scenes or if I'm overlooking so ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...

Notifier - The Best HTML Notification System for Web Applications

Currently, I am developing a notification system using Play Framework 2.3 (Java) in combination with MySQL. The system is designed to retrieve notifications from a "notifications" table stored in MySQL database. I initially attempted to use AJAX polling ...