You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Fail JSON.parse() data from Body of POST Request From Mobile Android Java
Success from Web Frontend with Typescript
Success from Postman (web frontend)
Picture of demonstrations is here:
Overview
We are building an app with using Nextjs(Typescript) as the backend and frontend(Nextjs is partially based on React).
For the mobile frontend, we are using Java Android. The okHttp3 is applied to send requests and receive responses.
We will have seperated frontends (web and mobile) and **only one backend API (web for handling all)
Scene
We want to realize user registration.
To be specific, when a user signup with the required information, the frontend will send POST request to backend. Then, the backend API will complete its job.
Problem
It works well with the web frontend and backend. Here is the code.
web frontend: a button onclick function in /signup
consthandleNext=(e: any)=>{if(step<4){setStep(step+1);}else{// submit user info into firebase auth and firestore user collectionsfetch("/api/auth/register",{method: "POST",body: JSON.stringify(formData)}).then((response)=>response.json()).then((data)=>{setSigned(true);setUid(data.uid);router.push("/onboardCompleted");}).catch((error)=>{console.log(error.message);});}};
web backend api: /api/auth/register
exportdefaultasyncfunctionhandler(req: NextApiRequest,res: NextApiResponse){try{constcheck=JSON.parse(req.body);}catch(e){returnres.status(400).json({error: "bad request since formData in undefined",body: req.body});}const{ createUserWithEmailAndPassword }=AuthService;constformData=JSON.parse(req.body);// 1. register user with email and password using firebase authconstuserCredential=awaitcreateUserWithEmailAndPassword(formData.email,formData.password);constuser=userCredential.user;if(!user||!user.uid){returnres.status(500).json({error: "firebase create user failed"});}try{awaitsetDoc(doc(db,"users",user.uid),{email: formData.email,focus: formData.focus,first_name: formData.firstName,last_name: formData.lastName,role: formData.role,goals: formData.goals,status: "freemium",created_at: Timestamp.now().toMillis(),free_sets: []});res.setHeader("set-cookie",`uid=${user.uid}; Max-Age=${1000*60*24*14};Path=/; HttpOnly`);returnres.status(200).json({uid: user.uid});}catch(e){returnres.status(500).json({error: "error setDoc in the firestore"});}}
These work well.
When adding the Android frontend, we have the following code:
StringmRequestBody = jsonBody.toString();
System.out.println("before post register");
post_register_request(mRequestBody, newCallback() {
@OverridepublicvoidonFailure(@NonNullCallcall, @NonNullIOExceptione) {
Log.i("\n\nFail on request register", call.toString());
}
@OverridepublicvoidonResponse(@NonNullCallcall, @NonNullokhttp3.Responseresponse) throwsIOException {
System.out.println("inside post register call back");
if (response.isSuccessful()) {
System.out.println("success post register call back");
Log.i("\n\nRequest sucessful", response.body().string());
}
else
{
System.out.println("not success post register call back");
Log.i("\n\nRequest not sucessful", response.body().string());
}
}
});
Callpost_register_request(Stringjson, Callbackcallback) {
System.out.println("start post register");
RequestBodybody = RequestBody.create(json, JSON);
okhttp3.Requestrequest = newokhttp3.Request.Builder()
.url(registerURL)
.post(body)
.build();
Callcall = client.newCall(request);
call.enqueue(callback);
System.out.println("finish return post register");
returncall;
}
The data is okay when sending from mobile end. But when backend receives request and parse the data in the body, it cannot be parsed, always fall into this code block of backend.
Here is the part of console result
Request not sucessful ]
{"error":"bad request since formData in undefined"}
Checking from Postman
We made the same POST request with the same data using Postman. It worked very well.
So it seems like the error is in the android part.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
TOO LONG DON'T READ
Picture of demonstrations is here:
Overview
We are building an app with using
Nextjs(Typescript)
as the backend and frontend(Nextjs is partially based on React).For the mobile frontend, we are using Java Android. The
okHttp3
is applied to send requests and receive responses.We will have seperated frontends (web and mobile) and **only one backend API (web for handling all)
Scene
We want to realize user registration.
To be specific, when a user signup with the required information, the frontend will send
POST
request to backend. Then, the backend API will complete its job.Problem
It works well with the web frontend and backend. Here is the code.
web frontend: a button onclick function in
/signup
web backend api:
/api/auth/register
These work well.
When adding the Android frontend, we have the following code:
The data is okay when sending from mobile end. But when backend receives request and parse the data in the body, it cannot be parsed, always fall into this code block of backend.
Here is the part of console result
Checking from Postman
We made the same POST request with the same data using Postman. It worked very well.
So it seems like the error is in the android part.
Do you have any ideas to solve this issue?
THANKS!
Beta Was this translation helpful? Give feedback.
All reactions