简体   繁体   English

使用 Express 服务器接收空请求

[英]Receiving an empty request with Express server

I'm having trouble receiving a simple object that's been turned into JSON.我在接收一个简单的 object 时遇到了问题,它已变成 JSON。 It shows up in the console.log as a {} , nothing more.它在console.log中显示为{} ,仅此而已。 I'll just refer to the server code:我将仅参考服务器代码:

const express = require("express");
const app = express();
app.listen(3000);
app.use(express.static("public"));
app.use(express.json());

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

And the index.html code:以及index.html代码:

        console.log("geolocation available");
        navigator.geolocation.getCurrentPosition((position) => {
          const lat = position.coords.latitude;
          const long = position.coords.longitude;

          const data = { lat, long };
          const options = {
            method: "POST",
            header: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify(data),
          };
          fetch("/api", options);
        });
      } else {
        console.log("geolocation not available");
      }

Thanks in advance!提前致谢!

You have a type in index.html, it should be "headers" not "header"您在 index.html 中有一个类型,它应该是“标题”而不是“标题”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM