javascript - 我正在尝试将 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);
});
解决方案
在您的客户端,您可以尝试此代码。您可以用您的端点替换 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);
})();
推荐阅读
- spring - spring 如何从资源映射中访问特定的一个文件
- python - 使用数组作为多维数组的索引掩码
- python - 如何在python中的正则表达式中获取组
- node.js - 如何在 aws 中为 node.js 运行 cron 作业
- ios - 在uitableview swift4中展开和折叠多级部分
- swift - 在 appdelegate 中添加一个 UITabbarController
- angular - 如何以角度将对象从服务返回到组件
- vue-chartjs - 如何始终显示工具提示?我正在使用 vue-chartjs v3.4
- tensorflow - “numpy.dtype”对象没有属性“base_dtype”
- mongodb - 如何用一个数组聚合多个文档?