【问题标题】:Getting empty object while POST request using fetch API使用 fetch API 在 POST 请求时获取空对象
【发布时间】: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


【解决方案1】:

你必须stringify你传递给fetchbody参数的对象(在这种情况下,在你的/public/main.js文件中):

const options = {
  method: "POST",
  header: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(pos),
};

【讨论】:

  • @SachinBhusal:你必须比这更具体。 “不工作”不是我们可以帮助您解决的问题描述。
  • @esqew 将 pos 更改为 JSON.stringify(pos) 仍然给我空对象。控制台记录来自服务器的响应,例如 fetch("/api", options) .then((res) =&gt; console.log(res)).catch((err) =&gt; console.log(err.message)); 向我显示错误说 Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. 如何解决这个问题?
【解决方案2】:

在将正文发送到服务器之前将其转换为字符串

//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>

【讨论】:

  • 我按照你说的转换成字符串,但是没有用。
  • 您可以通过控制台记录来自服务器的响应吗?
  • fetch("https://jsonplaceholder.typicode.com/posts", options).then(res =&gt; { console.log(res) }); 喜欢这个?
  • 不,我什么都没有
  • 当我将 .catch 也添加到 fetch("/api", options) .then((res) =&gt; console.log(res)) .catch((err) =&gt; console.log(err.message)); 这样的语句中时,我收到错误消息“Uncaught (in promise) TypeError: NetworkError when trying to fetch resource.”。
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多