首页 > 解决方案 > 我正在尝试将 JavaScript 数据发送到我的 NodeJS 服务器

问题描述

所以我试图通过 POST 请求将地理定位数据发送到 NodeJS,但是当我在我的 NodeJS 代码中控制台记录数据时,它只显示一个空对象。

我已经用邮递员测试了它,我可以毫无问题地接收数据。我认为问题出在我的应用程序的客户端

//**This is in the client Side(pure JS);

async function getWeather(position){

  let coords ={
    lat: position.coords.latitude,
    long: position.coords.longitude
  }

  const options = {
    method: "POST",
    body: JSON.stringify(coords),
    headers: {
      "Content-Type": "aplication/json"
    }
  };

  let response = await fetch("http://localhost:3000/weather", options);
  let location = await response.json();
}

.

//**This is in the server side

  app.post('/weather',(req,res)=>{

    let coords = req.body;
    console.log(coords); //This shows an empty object

    res.sendStatus(200);
  });

标签: javascriptnode.jsexpress

解决方案


在您的客户端,您可以尝试此代码。您可以用您的端点替换 url 并尝试获取结果。如下所示,我在data执行脚本后得到了响应。

我希望这有帮助。

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({lat: 10, long: 20})
  });
  const content = await rawResponse.json();

  console.log(content);
})();


推荐阅读