Not Getting anything back after calling Fetch API - React Native - react-native

I am creating a React Native in which i am sending my Form's data to Backend Node.js using Fetch and that worked all fine but i cannot execute anything down after fetch api, even console.log is not running.
React-Native Code:
const PostData = () =>{
console.log("Posting");
//Sending Request to Node.js using Fetch API
fetch("http://192.168.0.107:3000/Adminsignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({
name,
gmail,
password,
retype
})
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
}
.then and .catch of fetch api is not working.

Ok so your front-end code is all good and as u said that your backend is also working when you fire PostData() function, check if you are returning the response from backend.
Add this in your signup Route:
res.status(200).send({result:"Successfully got Response"})
Catch status in your front-end like this:
let final = await fetch("http://192.168.0.107:5000/studentSignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({name,gmail,password,retype})
})
const data = final.status;
if(data === 200)
{
navigation.navigate("Your Route");
}

Related

upload image from react native app to symfony backend via axios

I want to upload an image from react native app to backend in symfony via axios.
here is the code of the front end :
const [pickedImage, setPickedImage] = useState("");
const submitPhoto = async () => {
try {
const result = await ImagePicker.launchImageLibraryAsync();
setPickedImage(result);
let formData = new FormData();
formData.append("uploaded_image", {
uri:
Platform.OS === "android"
? pickedImage.uri
: pickedImage.uri.replace("file://", ""),
name: "tata.jpeg",
type: "image/jpeg",
});
const response = await axios({
method: "post",
url: "http://192.168.1.3:8000/upload",
data: formData,
});
} catch (error) {
console.log(error)
}
};
here is the code of the backend in Symfony :
public function postImage(Request $request)
{
//... some code
$content = $request->files->get("uploaded_image");
// ... handle the image in content
}
As I can see, $content is NULL. And to confirm it, I attached a screenshot of the profiler of symfony.
I tried to add "Content-type": "multipart/form-data" in the axios call, but i get : "Missing boundary in multipart/form-data POST data"
Does anyone know how I can properly upload the image from react native to Symfony ?
Thanks in advance.
EDIT 1 :
When using POSTMAN, the backend works as you can see in the two following images :
POSTMAN REQUEST :
PROFILER SYMFONY :
As I said, when i use Axios with the right header (multipart/form-data), I get a message error :
Missing boundary in multipart/form-data POST data
.
I tried to use fetch, and it works now ! I dont know why :
let response = await fetch(
"http://192.168.1.3:8000/upload",
{
method: "post",
body: formData,
headers : {
'Content-Type' : 'multipart/form-data;'
}
}
)
It is weird, but I dont know why it works now.
I think that you get a base64 in your back-end side, then you have to convert it with something like :
$data = base64_decode($content);
file_put_contents($filePath, $data);

Response to preflight request doesn't pass access control No 'Access-Control-Allow-Origin'

I have a Vue.js application that uses axios to send request to ApiGee Server.
This is the code i use to send request to APIgee.
const headers = {
'X-API-Key': 'randomKey123123'
}
return axios({
method: 'get',
url: url,
headers: headers
}).then(response => {
console.log(response)
})
from the ApiGee, I can see OPTIONS request being received first since I done the request from the client side browser.
I can also see the X-API-Key header key but the value is missing.
The error I'm getting from the browser console is
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Below code helped me you can try this format:
created() {
// POST request using axios with set headers
const article = { title: "Vue POST Request Example" };
const headers = {
'X-API-Key': 'randomKey123123'
};
axios.post(url, article, { headers })
.then(response => console.log(response.data)
);
}

React Native fetch POST variables not received on server

I have tried different ways with fetch or axios to POST to my server but it seems that the post body turns empty . My initial code is this.
So the connection to the server is good. I have configured server to respond with $_POST variables received but the $_POST return empty. This happens when I use JSON.stringify on body. I have also tried with FormData and it works fine but only on iOS. On my Android device and emulator I get Possible Unhandled Promise: Network request failed error (both https and http).
And I want to make it work on both iOS and Android. So till now I have manage to send post with formData only on iOS.
Any Solutions that works on Android and iOS?
import FormData from "FormData";
export const login = (emailUsername, password) => {
var formData = new FormData();
formData.append("emailUsername", emailUsername);
formData.append("password", password);
return async dispatch => {
const response = await fetch(
"https://myserver.net/api/app/auth.php",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
emailUsername:emailUsername,
password:password
})
}
);
if (!response.ok) {
throw new Error("Something went wrong!");
}
const resData = await response.json();
console.log(resData);
};
};
Thanks to #bug I have find a solution. I was expecting to receive POST content to my $_POST or $_REQUEST variables on my server, but instead I had to get them this way.
$post_data = json_decode(file_get_contents('php://input'));

Accessing the response from one GET request within another

I'm working with Vue to interact with an external API on a Drupal website, but in order to do so dynamically per Drupal user, I need to get a token from Drupal first. To do so, I'm trying to do two GET requests. The first gets me a bearer token out of Drupal, and the second uses it to authenticate the third-party API request.
Below is what I'm trying – I'm able to get the token successfully in the first request's response, but not when I try to use it in the header of my second request. If I try hardcoding the token that I see in the console log, it does work, so I know none of that is the issue. It's just that this.jwt['data']['token'] in the second request's headers seems to not pull back the token.
What do I need to adjust in order to access the token from the first response as part of the headers of my second request?
created() {
axios
.get('/jwt/token')
.then(response => {
this.jwt = response
console.log(this.jwt['data']['token']) // this does show what I want to access later
})
},
mounted() {
axios
.get('/comment/doc/' + this.id, {
headers: { Authorization: "Bearer " + this.jwt['data']['token'] } // ...but this doesn't work
})
.then(response => {
this.comments = response
})
},
It's likely the response to the token request has not finished by the time the component mounts, at which point this.jwt is not yet assigned.
I would move the token request into the mounted hook, fetching comments only when the token request succeeds:
export default {
mounted() {
axios
.get('/jwt/token')
.then(tokenResp => {
this.jwt = tokenResp
axios
.get('/comment/doc/' + this.id, {
headers: { Authorization: 'Bearer ' + this.jwt['data']['token'] }
})
.then(commentsResp => {
this.comments = commentsResp
})
})
}
}

Expo sdk 29/30: session cookie from login

In all prev versions of Expo, I used RN fetch method to POST username/password to a Flask login endpoint. This endpoint saved user info to the session and set session cookie. It was always transparent and I never had to pass anything extra.
This worked as of Expo v28. But when I upgraded to Expo 30, the server no longer sees the client as logged in. Do I need to change how I use fetch? Do I need to pass some extra parameters?
First, before login, we need to clear the old cookies using:
import { NativeModules } from 'react-native'
const Networking = NativeModules.Networking;
Networking.clearCookies((cleared) => {
console.debug('cleared hadCookies: ' + cleared.toString());
ApiUtils.login(your_login_parameters); // your login function
});
We have to clear the cookies because the native cookie manager is sending stale cookies. Now, we will manage the cookie ourselves.
In my login handler, I use set-cookie-parser to parse the cookies sent by the server in the 'set-cookie' response header.
import setCookie from 'set-cookie-parser';
// insider my login handler
const response = await fetch(login_endpoint, credentials_payload);
let cookies, cookieHeader, serverData;
if (response.ok) {
serverData = await response.json();
cookieHeader = setCookie.splitCookiesString(response.headers.get('set-cookie'));
cookies = setCookie.parse(cookieHeader);
console.log(cookies); // array
// Save cookies array to SecureStore or AsyncStorage
}
Finally, for all requests to the server that require session cookie, we send the cookie in the fetch headers.
const makeFetchParams = (form_data) => {
const cookies = get_from_storage_of_choice // SecureStore or AsyncStorage
const c_arr = cookies.map(d => { return d.name+'='+d.value; });
const cookieStr = c_arr.join(';');
return {
method: 'POST',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'cookie': cookieStr
},
body: form_data
};
};
// inside endpoints that require the session cookie
const response = await fetch(your_url, makeFetchParams(some_form_data));
I tested this with Expo SDK v30 and Android. This is works-for-me solution may be of use to others.