Skip to content Skip to sidebar Skip to footer

A Problem With A Post Method (using Fetch And Express)

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.

Solution 1:

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


Post a Comment for "A Problem With A Post Method (using Fetch And Express)"