【问题标题】:What's the domain name of my node.js server?我的 node.js 服务器的域名是什么?
【发布时间】:2020-12-13 20:49:28
【问题描述】:

我正在尝试从服务器获取数据到我的颤振应用程序。这是我在 Node.js 中的服务器端代码:

const express=require('express');
const app=express();
app.use(express.json());
const getres='himu you got the request';
app.post('/post',async(req,res,next)=>{
const name= req.body.name;
console.log(name);
next();
}
);

app.get('/get',async(req,res,next)=>{
res.end('hello world');
res.json('hey from nodejs');
next();
}
);

app.listen(3000);

这是我的颤振代码,我试图从服务器获取一个字符串,但是当我在颤振控制台中打印时字符串返回 null。我很困惑我的 DOMAIN 应该是什么。

const PROTOCOL = "http";
const DOMAIN = "localhost:3000";

Future<RequestResult> http_get(String route, [dynamic data]) async
{
  var dataStr = jsonEncode(data);
  var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
  var result = await http.get(url);
  return RequestResult(true, jsonDecode(result.body));
}

这里我正在尝试打印数据

 Future<void> getdata() async {
   var result= await http_get('get');
   print(result.data);
  }

【问题讨论】:

    标签: node.js json express flutter server


    【解决方案1】:

    当您说服务器在您的 Flutter 也在运行的本地机器上时

    如果是,那么您的域是 localhost:3000

    else domain name 是您的 Node 代码托管和运行的服务器的 IP,(如果您的 DNS 使用 IP 掩码,您可以使用 http://myserver.com 之类的名称,myserver 是您假设掩码的域名)

    如果你的 Flutter 应用在​​移动设备上运行并且 nodeJs 在本地机器上运行,你需要和你的机器在同一个网络上才能访问 localhost:3000

    【讨论】:

    • 我正在使用我的手机热点连接到互联网,服务器正在运行,flutter 应用程序也在移动设备上运行。
    • 你的 node.js 服务器在哪里运行?
    • 它现在可以工作了,我只是复制了我连接的 IPv4 地址并将其用作域名。不过,感谢您解释清楚的答案。
    • 如果它在你的本地机器上,找到系统的IP地址(ipconfig在windows上给出),用谷歌搜索你的操作系统,在Flutter localhost将指向你的移动设备localhost,它不是你的服务器localhost,你需要使用机器的IP地址
    【解决方案2】:

    如所见,域没有问题,尝试去掉url变量中的查询参数

    const PROTOCOL = "http";
    const DOMAIN = "localhost:3000";
    
    Future<RequestResult> http_get(String route, [dynamic data]) async
    {
      var dataStr = jsonEncode(data);
      var url = "$PROTOCOL://$DOMAIN/$route?data=$dataStr";
      var result = await http.get(url);
      return RequestResult(true, jsonDecode(result.body));
    }
    

    这里您的查询参数?data=$dataStr 不可用,因为您只设置了路由而不是后端的查询。
    您可以将您的获取请求发送到/get route

    【讨论】:

      猜你喜欢
      • 2021-12-09
      • 1970-01-01
      • 2019-05-14
      • 2017-05-21
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多