2

I'm a very beginner so I hope my question is not that stupid. What I want to do is to pass a longitude and a latitude from a client-side javascript into a node.js on a server-side. I'm using a fetch and express.js.

Below my html code:

<!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 little sample from my 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('/api', options);
      });
}  else {  
        console.log('geolocation not available');
      }
}); 

And here you can see my node.js code:

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 it I receive an 404 error. I have no idea what I'm doing wrong here. I'll be grateful for any advice.

EDIT:

This app is working on my VPS. I also have a domain with SSL aliases. To run node.js I use nodemon 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 a process.

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

As you can see I'm working on centOS7

macpan
  • 93
  • 7
  • Hi, can you post a bit more information about how are you serving the frontend app? Also, some logs from the backend server would also be helpful to debug. – Yuvraj Jaiswal Oct 20 '20 at 16:28
  • Are you also serving the client-side from your NodeJs application? If not I'd suggest taking a look at this website http://expressjs.com/en/starter/static-files.html – fabrv Oct 20 '20 at 17:07
  • You should pass the whole URL to fetch – MWO Oct 20 '20 at 17:45
  • I made an edit to add some details about my app. – macpan Oct 21 '20 at 09:32

1 Answers1

0

Try to add full path for the fetch. You are listening server at localhost on the 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 everting is ok should log the object  message: "Long lang sent to express" from server
            console.log(data)
        });
  });
...

And server side will be like dat

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 go wrong, try again' })
   }
});

Trying to use lowercase variables(example: not use X, Y.. but use x, y) if it not a constants :) Gl with programming

  • 1
    Thanks for the answer. I made a full path for the fetch. I tried to use localhost, my domain name and IP of my VPS server but it all seems not to work. I still have an 404 error. – macpan Oct 21 '20 at 09:21
  • sorry, it's not 404 error. thats: "Cross-Origin Request Blocked" which is kind of weird because I do POST request on the same domain – macpan Oct 22 '20 at 19:02