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'));
Related
I am trying to use the composition api on my Vue app, and I need to do a post request to my backend api. I am trying to make use of the "useAxios" utility from vueuse, but I can't figure out how to pass data into a post request. It isn't shown properly in the docs...
I want to convert the following axios request into one that uses "useAxios".
await axios.put(`/blog/posts/${route.params.postID}/`, post.value)
.then(() => notification = "Post Created!")
.catch(() => {
error = "Failed to create post"
});
I tried setting the value of the data field, but that didn't work...
const {data, execute, isFinished} = useAxios(axios)
data.value = post
await execute(`/admin/blog/posts/${route.params.postID}/`, {method: "PUT"})
I also tried passing the post object into the execute method as a parameter, but my ide complained.
Thanks in advance!
Set up your pending request ahead of time:
const { data, execute, isFinished } =
useAxios(`/admin/blog/posts/${route.params.postID}/`,
{ method: "PUT" },
{ immediate:false });
Then in the future you can call it by passing the data as follows:
const requestBody = { /* your data */ };
await execute({ data: requestBody });
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);
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");
}
i'm using api platform to create end Point to handle images upload.
My api require a file type to make a post request.
This is an example of post request using post man :
I want to handle sending images with axios using react native.
I created a post request like this :
this.setState({
avatarSource: source,
});
console.log(this.state.avatarSource.uri);
const data = new FormData();
data.append('file', {
uri: this.state.avatarSource.uri,
// show full image path in my device
// file:///storage/emulated/0/Pictures/image-c40b64fc-6d74-46a7-9016-191aff3740dd.jpg
});
axios
.post(`${API.URL}/media_objects`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((resp) => console.log(resp))
.catch((err) => console.log(err.message));
}
});
I'm sending the full path of image in my phone to the api but i got "Network Error"
I fixed the problem by commenting this line in ReactNativeFlipper.java :
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
#Override
public void apply(OkHttpClient.Builder builder) {
// builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin)); // add comment here and build android
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
I have made an API using lumen and all POST,GET Methods are working well in localhost and also works GET request when hosted on live server but unfortunately POST request are not working and shows the error as
net::ERR_HTTP2_PROTOCOL_ERROR
The POST request is working well in POSTMAN
async submitForm(){
const config = {
headers: { 'content-type': 'application/json','Accept':'application/json','Access-Control-Allow-Origin':'*'}
}
let formData = new FormData();
formData.append('name', this.name);
formData.append('email', this.email);
formData.append('phone', this.phone);
formData.append('message', this.message);
await this.$axios.$post('https://myurl',formData,config)
.then((response) => {
this.success = 'Thank you !!';
})
.catch((error) => {
this.error = 'Unable to submit . Please try again later .';
});
}