使用flutter客户端向node.js express api发出post请求

时间:2021-07-06 19:27:37

标签: javascript node.js json flutter http

这是我的第一个问题,因此对于此平台上的任何菜鸟错误,我提前道歉。

我正在使用 Express.js 使用 Firebase Cloud Functions 创建 API。我正在尝试让 Flutter 与此 API 通信以注册用户。当我在 Postman 中测试我的 API 时,一切正常。我使用原始 JSON 数据发送我的请求,响应为我提供了一些我希望在客户端上显示的帐户信息的 JSON 对象。

我将 VSCode 用于所有这些,并使用 Web 调试器调试 Flutter 代码。

我环顾四周并尝试了两种解决方案,但它们各自有错误。第一种方法:

var response = await http.post(uri, body: {
  'email': 'bob@email.com',
  'username': 'BoB',
  'password': 'password',
  'passwordConfirm': 'password',
});

我让 Error: XMLHttpRequest error. 这样做。当我尝试在 http.post 函数中使用这种方法设置标头时,我收到了 Error: Bad state: Cannot set the body fields of a Request with content-type "application/json".

headers: <String, String>{'content-type': 'application/json',},

在本网站上阅读了一些内容后,我发现了第二种方法:

HttpClient httpClient = new HttpClient();
var jsonMap = {
  'email': 'bob@email.com',
  'username': 'BoB',
  'password': 'password',
  'passwordConfirm': 'password',
};
HttpClientRequest request = await httpClient.postUrl(uri);
request.headers.add('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
httpClient.close();

希望第一种方法只是删除了一些必要的标题,然而,这个方法产生了 Error: Unsupported operation: Platform._version 所以我尝试更新 Flutter,但收到同样的错误。

API 代码如下所示:

const functions = require("firebase-functions");
const signup = require("./handlers/signup");
const app = require("express")();
const cors = require("cors");
app.use(cors());

app.post("/signup", signup);

exports.api = functions.https.onRequest(app);

注册处理程序所做的第一件事是将请求记录到控制台,而我尝试过的任何事情都没有做到这一点。

我使用 localhost 来提供 firebase 功能并运行 flutter 客户端。

我还尝试在 http.post 请求中发送纯文本/文本,并让处理程序将其解析为一个对象,以便与我已有的代码一起使用,但是,该请求并未发送到处理程序。我没有保存代码或我以这种方式收到的错误。即使使用 Postman,我也无法使用这种方法。

感谢您的帮助。如果您需要更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

如图所示将内容类型设置为 x-www-form-urlencoded 有效:

var response = await http.post(
  Uri.parse(
      'http://localhost:5000/fadenworlddev/us-central1/api/signup'),
  headers: <String, String>{
    'Content-Type':
        'application/x-www-form-urlencoded; charset=UTF-8',
  },
  body: <String, String>{
    'username': 'BoB',
    'email': 'Bob@email.com',
    'password': 'password',
    'passwordConfirm': 'password',
  },
);
相关问题