【发布时间】:2021-08-02 18:51:39
【问题描述】:
我是 express/Node.js 方面的新手。我尝试发布包含当前用户位置的请求(使用地理定位 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);
});
index.js 上方是服务器代码。当我在终端中运行 index.js 时,我得到了以下输出。
I got request!
{}
但在浏览器控制台中,Object { latitude: 27.6430848, longitude: 84.115456 } 正在显示。这意味着 pos 不是空对象。那么为什么它在服务器端显示空对象。提前谢谢你。
【问题讨论】:
-
虽然这不应该成为问题,但请注意
navigator.geolocation.getCurrentPosition是异步的。希望在单击按钮时在pos上设置属性不是一个好方法。最好将逻辑放在可以从事件处理程序调用的函数中,让它返回(解析到的承诺)位置。 -
JavaScript 对象不是 JSON。
-
@FelixKling 我在事件侦听器函数中做了控制台日志,它向我显示了我上面提到的 pos 对象。所以我不认为这是因为
geolocation.getCurrentPosition函数的异步属性。 -
这就是为什么我说“虽然这里不应该是个问题”。最好以不同的方式构建它,这样您在更改代码时就不会遇到这个问题。
标签: javascript node.js express server-side fetch-api