【发布时间】:2020-07-21 06:17:14
【问题描述】:
我对 fetch 有一些问题,特别是 POST 方法。我有登录功能来登录应用程序,但是当我输入用户名和密码时,错误显示如下。这个项目就像从 Android Studio 迁移/重写到 React Native。注意:email、password、device_id 和 fcm_token 从应用程序中加密,并作为加密字符串发送到服务器。
另外,我也在 Postman 上对它进行了测试,并在正文中使用了加密字符串,并且它可以工作。有什么建议为什么会引发错误?谢谢。
这是 React Native 中获取登录 API 的代码
LoginEmail.js
...
await fetch(ApiUrl.login, {
method: "POST",
headers: new Headers({
"Accept": "application/x-www-form-urlencoded",
"Content-Type": "application/x-www-form-urlencoded",
"Eventku-Api-Key": AppData.apiKey
}),
body:
JSON.stringify( {
"&email=": cipherEmail.toString(),
"&password=": cipherPass.toString(),
"&device_id=": cipherDevice.toString(),
"&fcm_token=": cipherToken.toString()
})
}).then(response => response.text()).then(responseJson => {
...
这是用于登录的 Java 代码
ApiServices.java
...
//login using email
@FormUrlEncoded
@POST("login")
Call<ResponUser> login(
@Field("email") String email,
@Field("password") String password,
@Field("device_id") String device_id,
@Field("fcm_token") String fcm_token
);
...
LoginActivity.java
...
apiServices.login(
Strings.encryptData(edtEmail.getText().toString()),
Strings.encryptData(edtPassword.getText().toString()),
Strings.encryptData(imeiNumber),
Strings.encryptData(fcm.getString(getString(R.string.FCM_TOKEN),""))
).enqueue(new Callback<ResponUser>() {
...
【问题讨论】:
-
不知道您的标题(所有名称看起来都不错),但您绝对不想使用
JSON.stringify()发布application/x-www-form-urlencoded格式化数据 -
@Phil 我可以知道为什么吗?如果我用
"&email=" + cipherEmail.toString() +之类的东西改变身体,可以吗? -
为什么?因为
JSON.stringify生成 JSON,但您没有发布 JSON。搜索如何在 React Native 中最好地创建application/x-www-form-urlencoded字符串。在浏览器中,我只使用URLSearchParams,但我不知道你是否可以使用 -
@Phil gist.github.com/juskangkung/6f0dbabc24c70413d075ae2605d8a50d 向您发送我的 BE 使用的控制器文件
标签: javascript java react-native fetch