【问题标题】:Flutter Dart HTTP POST request body is empty on server sideFlutter Dart HTTP POST 请求正文在服务器端为空
【发布时间】:2020-01-09 10:41:42
【问题描述】:

我正在开发一款 Flutter 平板电脑应用。一旦输入了一个输入字段,我就会尝试向服务器发送一个发布请求。以下是我为此调用的方法:

    Future < http.Response > _postRequest() async {
    print(globals.novaCoord.toString() + ' XYZXYZXYZXYZXYZ');

    var url = globals.URL + 'api/nova_position';

    Map data = {
      'id_nova': '1',
      'position.x': '1',
      'position.y': '1',
      'position.z': '1',
      'position.pitch': '1',
      'position.yaw': '1',
      'position.roll': '1',
    };
    //encode Map to JSON
    var body = json.encode(data);

    http.Response response = await http.post(url,
      headers: {
        "Content-Type": "application/json"
      },
      body: body
    );
    print("${response.statusCode}");
    print("${response.body}");
    return response;
  }

在 NodeJs 服务器端我有这个:

app.post('/api/nova_position/', async (req,res) => {
    console.log("NOVA POSITION");
    console.log(req.body.id_nova);
    const id_nova = req.body.id_nova;
    const x = req.body.position.x;
    const y = req.body.position.y;
    const z = req.body.position.z;
    const pitch = req.body.position.pitch;
    const yaw = req.body.position.yaw;
    const roll = req.body.position.roll;

    const position = await db.db.create_position(id_nova,x,y,z,pitch,yaw,roll);
});

但是,在服务器端,我收到的请求的“正文”为空,并且收到以下错误:

(node:23939) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'x' of undefined

此时我需要帮助。感谢您的帮助和指导。

【问题讨论】:

  • 你在哪里打电话给http.createServer?那个代码在哪里?你能用 Postman 锻炼你的服务器吗?
  • 嗨@RichardHeap 我有一个nodeJs 服务器,即使我尝试使用PostMan,我也看到服务器不知何故有一个空的“body”。我只需要确保服务器端。

标签: flutter dart


【解决方案1】:

使用http.post 发送Map&lt;String,dynamic&gt; 将无法正确发送您的数据。

要解决这个问题,请将标头的内容类型更改为:

Map<String, String> customHeaders = {
...
"content-type": "application/json"
...
};

然后,您可以使用http.post,如下所示:

http.post(url, headers: customHeaders, body);

【讨论】:

    【解决方案2】:

    你必须在推入 Post 请求之前进行 jsonEncode 喜欢

    String bodyF = jsonEncode(body);
    

    我希望你能得到你的解决方案。

    【讨论】:

    • 是的,你是对的。完成建议的修复后,我有一个更新的代码。我现在确定我有关于服务器的问题。从 PostMan 收到的正文也是空的。
    【解决方案3】:

    我找到的解决方案只是将Content-Length : x 添加到您的标题中,x 是您的 json 正文的大小。

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 2020-02-10
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 2020-06-13
      • 1970-01-01
      相关资源
      最近更新 更多