【问题标题】:A problem with a post method (using fetch and express)post 方法的问题(使用 fetch 和 express)
【发布时间】:2020-10-21 17:34:07
【问题描述】:

我是一个非常初学者,所以我希望我的问题不是那么愚蠢。 我想要做的是将经度和纬度从客户端 javascript 传递到服务器端的 node.js 中。我正在使用 fetch 和 express.js。

在我的html代码下面:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  </head>
  <body>
      latitude: <span id="latitude"></span>&deg;<br />
      longitude: <span id="longitude"></span>&deg;<br />
    </p>
    <button id="geolocate">geolocate</button>
    <script src="main.js"></script>
  </body>
</html>

这是我的 main.js 中的一个小示例:

document.getElementById('geolocate').addEventListener('click', event => { 

    if ('geolocation' in navigator) { 
        console.log('geolocation available');
        navigator.geolocation.getCurrentPosition(position => {                    
            var X = position.coords.latitude;   
            var Y = position.coords.longitude;
            console.log(X, Y);
            document.getElementById('latitude').textContent = X;
            document.getElementById('longitude').textContent = Y;
            
             const data = {X, Y}
             const options = {
                method: 'POST',
                body: JSON.stringify(data),
                headers: {
                    'content-type': 'application/json'
                 }
             }
        fetch('/api', options);
      });
}  else {  
        console.log('geolocation not available');
      }
}); 

在这里你可以看到我的 node.js 代码:

const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at 3000'));

app.post('/api', (req, res) => {
  console.log(req);
});

当我运行它时,我收到一个 404 错误。我不知道我在这里做错了什么。如有任何建议,我将不胜感激。

编辑:

这个应用程序正在我的 VPS 上运行。我还有一个带有 SSL 别名的域。为了运行 node.js,我使用 nodemon 作为进程。以下是日志:

user_name_with_sudo  11451  0.5  3.6 663672 38152 pts/0    Sl+  11:05   0:00 node /bin/nodemon index.js $

如您所见,这是一个过程。

httpd service status - Oct 20 17:14:21 www.{my domain}.pl systemd[1]: Started The Apache HTTP Server. 

如你所见,我正在开发 centOS7

【问题讨论】:

  • 嗨,您能否发布更多关于您如何为前端应用程序提供服务的信息?此外,后端服务器的一些日志也有助于调试。
  • 您是否也在为您的 NodeJs 应用程序提供客户端服务?如果没有,我建议看看这个网站expressjs.com/en/starter/static-files.html
  • 你应该传递整个 URL 来获取
  • 我进行了编辑以添加有关我的应用的一些详细信息。

标签: javascript node.js express post fetch


【解决方案1】:

尝试添加获取的完整路径。您正在 localhost 的 3000 端口上侦听服务器

main.js:

document.getElementById('geolocate').addEventListener('click', event => { 

if ('geolocation' in navigator) { 
    console.log('geolocation available');
    navigator.geolocation.getCurrentPosition(position => {                    
        var X = position.coords.latitude;   
        var Y = position.coords.longitude;
        console.log(X, Y);
        document.getElementById('latitude').textContent = X;
        document.getElementById('longitude').textContent = Y;
        
         const data = {X, Y}
         const options = {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'content-type': 'application/json'
             }
         }
    fetch('http://localhost:3000/api', options)
        .then(response => response.json())
        .then(data => {
            // if everting is ok should log the object  message: "Long lang sent to express" from server
            console.log(data)
        });
  });
...

服务器端就像 dat

const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening at 3000'));

app.post('/api', (req, res) => {
  try {
      const {X, Y} = req.body
      console.log(X, Y)
      res.status(200).json({ message: "Long lang sent to express" })
   } catch (e) {
       res.status(500).json({ message: 'Something go wrong, try again' })
   }
});

如果不是常量,则尝试使用小写变量(例如:不使用 X、Y.. 但使用 x、y) :) Gl 与编程

【讨论】:

  • 感谢您的回答。我为获取做了一个完整的路径。我尝试使用 localhost、我的域名和我的 VPS 服务器的 IP,但似乎都不起作用。我仍然有 404 错误。
  • 抱歉,不是 404 错误。那是:“跨域请求被阻止”这有点奇怪,因为我在同一个域上做 POST 请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-22
相关资源
最近更新 更多