0

I am a newbie in express/Node.js things. I tried to post a request containing the current user location(longitude and latitude using geolocation api).

/public/index.html

<!DOCTYPE >
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hey</title>
  </head>
  <body>
    <h1>Welcome</h1>
    <button id="submit" class="click-btn">Submit my Location</button>
    </div>
    <script src="main.js"></script>
  </body>
</html>

/public/main.js

//navigating the user's current location using geolocation web api
const pos = {};
if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (location) => {
      pos.latitude = location.coords.latitude;
      pos.longitude = location.coords.longitude;
    },
    (err) => console.log(err.message)
  );
} else {
  console.log("oops");
}

// handling submit location to send
// latitude, longitude to the server we created
const submit_button = document.getElementById("submit");

submit_button.addEventListener("click", (e) => {
  e.preventDefault();
  const options = {
    method: "POST",
    header: {
      "Content-Type": "application/json",
    },
    body: pos,
  };
  console.log(pos);
  fetch("/api", options);
});

/index.js

const { json } = require("express");
const express = require("express");
const app = express();

app.listen(3000, () => console.log("listeninig...."));
app.use(express.static("public"));
app.use(express.json({ limit: "1mb" }));

app.post("/api", (request, response) => {
  console.log("I got request!");
  console.log(request.body);
});

Above index.js is server code. When I run index.js in the terminal I got the following output.

I got request!
{}

But in browser console, Object { latitude: 27.6430848, longitude: 84.115456 } is showing. That means pos is not empty object. So why is it showing empty object in server side. Thank you in advance.

4
  • While that shouldn't be a problem here, note that navigator.geolocation.getCurrentPosition is asynchronous. Hoping that the properties will be set on pos by the time the button is clicked isn't a good approach. Better put the logic in a function that can be called from the event handler have it return (a promise that resolve to) the position. Commented May 12, 2021 at 12:01
  • A JavaScript object is not JSON. Commented May 12, 2021 at 12:01
  • @FelixKling I did console log inside event listener function and it's showing me pos object as I mentioned above. So I dont think its because of asyncronous property of geolocation.getCurrentPosition function. Commented May 12, 2021 at 13:30
  • That's why I said "While that shouldn't be a problem here". It's still better to architect this differently so that you will never run into this issue when you change your code. Commented May 12, 2021 at 14:26

2 Answers 2

1

You have to stringify the object you pass to fetch’s body parameter (in this case, in your /public/main.js file):

const options = {
  method: "POST",
  header: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(pos),
};
Sign up to request clarification or add additional context in comments.

2 Comments

@SachinBhusal: You have to be more specific than that. "not working" is not a problem description that we can help you with.
@esqew Changing pos to JSON.stringify(pos) is still giving me empty object. And console log the response from the server like fetch("/api", options) .then((res) => console.log(res)).catch((err) => console.log(err.message)); is showing me error saying Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. How to resolve this?
0

Convert your body to a string before sending it to the server

//navigating the user's current location using geolocation web api
const pos = {};
if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (location) => {
      pos.latitude = location.coords.latitude;
      pos.longitude = location.coords.longitude;
    },
    (err) => console.log(err.message)
  );
} else {
  console.log("oops");
}

// handling submit location to send
// latitude, longitude to the server we created
const submit_button = document.getElementById("submit");

submit_button.addEventListener("click", (e) => {
  e.preventDefault();
  const options = {
    method: "POST",
    header: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(pos),
  };
  fetch("http://localhost:3000/api", options).then(res => {
    console.log(res)
  });
});
<!DOCTYPE >
<html>

<head>
  <meta charset="UTF-8" />
  <title>Hey</title>
</head>

<body>
  <h1>Welcome</h1>
  <button id="submit" class="click-btn">Submit my Location</button>
  </div>
  <script src="main.js"></script>
</body>

</html>

7 Comments

I converted to a string as you said but not working.
Can you console log the response from the server?
fetch("https://jsonplaceholder.typicode.com/posts", options).then(res => { console.log(res) }); Like this?
No i got nothing
When i added .catch too to that statement like fetch("/api", options) .then((res) => console.log(res)) .catch((err) => console.log(err.message)); then I got error saying `Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.'.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.