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.
navigator.geolocation.getCurrentPositionis asynchronous. Hoping that the properties will be set onposby 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.geolocation.getCurrentPositionfunction.