I want to upload photos with React Native. My API attempt from Postman resulted in a positive.
But React Native didn't make it.
React Native function
uploadPhoto = async response => {
const data = new FormData();
data.append("image", {
uri: response.uri,
type: response.type,
name: response.fileName,
length:response.fileSize
});
const config={
headers:{
'Content-type':'multipart/form-data'
}
}
axios
.post('https://localhost:44337/api/values',JSON.stringify(data),config)
.then(response=>{
console.log(response);
})
.catch(error=>{console.log(error);})
};
Asp.net Core side
[HttpPost]
public IActionResult Post([FromForm]PhotoModel bookData)
{
//installation codes
return Ok();
}
Model
public class PhotoModel
{
public IFormFile image { get; set; }
}
Result:Network Error
You can try in react native code.
Hope helpful for you.
export const uploadImages = async (formData) => {
try {
let response = await axios({
url: urlUploadImages,
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, GET, PUT, OPTIONS, DELETE',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Methods, Access-Control-Allow-Origin, Origin, Accept, Content-Type',
'Accept': 'application/x-www-form-urlencoded',
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + global.TOKEN || 'Bearer ' + await AsyncStorage.getItem("#loggedInUserID:token"),
},
data: formData,
});
console.log('uploadImages API response', response)
if (response.status === 401) {
return global.UNAUTHORIZE;
} else {
// let json = await response;
if (response.status === 200) {
return response.data;
} else {
return global.FAIL;
}
}
} catch (error) {
console.log('Upload Failed', error);
}
};
You don't have to change from form data back to JsonString. Send it right away.
.post('https://localhost:44337/api/values',data,config)
Remove json.stringify and verify that you set right values:
const form = new FormData();
form.append('image', {
uri: "file:///...",
type: 'image/jpg',
name: 'image.jpg',
});
Related
in React native can anyone tell me how to make the responsePath optional thats how i make it optional using && but it is not working in case of photo field can anyone help me out below are the codes.first is of redux how i send the data using formdata and 2nd is of component where i called this api function of redux.
redux//
export const addMember = (formValues, actions, key, resourcePath) => {
return async dispatch => {
const token = await AsyncStorage.getItem('userToken');
const formdata = new FormData();
formdata.append('name', formValues.name);
formdata.append('age', formValues.age);
formdata.append('relation', formValues.relation);
formdata.append('gender', key);
formValues.mobile && formdata.append('mobile', formValues.mobile);
formValues.blood_group &&
formdata.append('blood_group', formValues.blood_group);
formValues.height && formdata.append('height', formValues.height);
formValues.weight && formdata.append('weight', formValues.weight);
formValues.email && formdata.append('email', formValues.email);
resourcePath && formdata.append('photo', resourcePath);
console.log(formdata, 'for mdata');
let response = await fetch(
'https://theeasylab.com/admin/api/auth/add-family-member',
{
method: 'post',
body: formdata,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
},
)
.then(res => {
return res;
})
.catch(error => {
actions.setErrors(error?.response?.data.error);
return error.response;
});
dispatch({
type: 'ADD_MEMBER',
payload: response,
});
};
};
component //
submitAddMemeber = (values, actions) => {
this.props
.addMember(
values,
actions,
this.state.itemValue.key,
this.state.resourcePath
)
};
I am trying to call the hasnode API to get blogs as the response, the body is in GraphQL. But I get this error in the Network Tab 'POST body missing. Did you forget use body-parser middleware?'
`
let query = `
{
user(username: "singhmona") {
publication {
posts{
slug
title
brief
coverImage
}
}
}
}
`;
let body = JSON.stringify({
query
});
axios
.post('https://api.hashnode.com/',
body,
{
'content-type': 'application/json',
})
.then(response => {
this.info = response;
console.log(response);}
)
`
I think you should try using fetch. I've had a tough one with axios when using it in node and I was finally able to get the api to work with fetch. Here is a snippet of what worked for me.
const getData = async() => {
const query = `
{
user(username: "misiochaabel") {
publication {
posts(page: 0) {
slug
title
brief
coverImage
}
}
}
}
`;
const response = await fetch('https://api.hashnode.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const data = await response.json();
console.log(data);
}
I need to fetch data from pass parameter in below format, because when test in Postman then only this format gives response.
"json": {"model":"DB11 AMR","modelyear":"2019","locale":"AA"}
Can you please help to fetch data from below server url.
https://vhapp.azurewebsites.net/myAMLModelSelection
Below is my code
var url = 'http://vhapp.azurewebsites.net/myAMLModelSelection'
try {
let response = fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"json" : { "locale": "AA", "model" : "DB11 AMR", "modelyear" : "2019" }
})
})
.then(res => res.text()) // convert to plain text
.then(text => {
console.log(text)
alert(text)
var res = text.substring(1, text.length-2);
var obj = JSON.parse(res);
alert(obj.cars[0].name)
})
.catch((error) => {
console.error(error);
});
} catch (errors) {
console.log(errors);
}
Here is my response which i need
({"cars":[{"name":"DB11 AMR","content":{"guide":"http://cdntbs.astonmartin.com/360ss/OwnersGuides/KY53-19A321-AC.pdf","assets":[{"intAssetId":"115","intVehicleId":"1","strType":"pdf","strName":"Accessories Brochure","strDescription":null,"strLocation":"http://cdntbs.astonmartin.com/360ss/iPad/myaml/brochures/Accessories Brochure English - 706435-PK.pdf","intVersion":"1","intOrder":"1"}]}}]});
You can fetch the data using JS fetch API.
export async fetchMyData(){
try{
let f = await fetch('https://vhapp.azurewebsites.net/myAMLModelSelection',{method:'GET'})
let data = await f.json();
return data;
}catch(err){
console.log(err)
}
}
And Call this method in your component like:
import {fetchMyData} from './file_name'
fetchMyData().then((response)=>{console.log(response)})
I have a doFetch function that handles all my api calls:
const doFetch = function(params){
...
// Make request using Axios. Axios is promise based.
return axios({
method: method,
url: baseUrl + url,
data: queryParams,
timeout: timeout,
headers: {
'Content-Type': contentType,
'Authorization': `bearer ${Auth.getToken()}` // set the authorization HTTP header
},
responseType: responseType
}).then((response) => {
if(typeof params.callback === "function"){
params.callback(response);
}
else {
return response;
}
}).catch((err) => {
if(typeof params.error === "function") {
if (err.response) {
params.error(err.response.data);
}
}
else{
if (err.response) {
return err.response.data;
}
else{
return err;
}
}
});
};
One such api call is returning a custom error like so (express server):
return res.status(400).json("There was an error on the server.");
The function that calls doFetch is saveUser:
saveUser(userObj).then((response) => {
console.log("No Error");
}).catch((error) => {
console.log("Error:", error);
});
The problem is that I am seeing No Error in the terminal, when I should only be expecting the error message to show. Any ideas?
I like to return promise exactly, to be sure that it does/returns what I want.
I don't like to rely on "promise"-s of 3rd parties.
So I would recommend You to wrap it inside of promise and resolve/reject responses/errors manually:
const doFetch = params => {
...
// Make request using Axios. Axios is promise based.
return new Promise((resolve, reject) => {
axios({
method: method,
url: baseUrl + url,
data: queryParams,
timeout: timeout,
headers: {
'Content-Type': contentType,
'Authorization': `Bearer ${Auth.getToken()}` // set the authorization HTTP header
},
responseType: responseType
})
.then((response) => {
console.info('doFetch:', response); // for debug purposes
if(typeof params.callback === "function"){
params.callback(response);
}
resolve(response);
})
.catch((err) => {
console.error('doFetch:', err); // for debug purposes
const error = (err.response) ? err.response.data : err;
if(typeof params.error === "function") {
params.error(error);
}
reject(error);
});
};
};
I have this fetch() method that is sending data from my react-native app to a laravel method
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
//let res = await response.text();
if (response.status >= 200 && response.status < 300) {
console.log(response);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
I can receive the data using this method
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData);
//parse_str($postedValue, $output);
return response()->json([
'name' => $postedValue,
'route' => $postedValue
]);
}
and attempting to return the just posted data. The posted data looks like this
12:35:07 PM:
{"type":"default","status":200,"ok":true,"headers":{"map":{"connection":["Keep-Alive"],"content-length":["54"],"content-type":["application/json"],"set-cookie":["XSRF-TOKEN=eyJpdiI6IlF1NWlLOE9rVCtlUXNpYzBFSTV0c0E9PSIsInZhbHVlIjoiNWtGenprRmJOYTVsc2dQRjNrcmpxZXhWeFZRd1NZSzdiOWFKUUZTZmJJaEN6U0RnbW9uOVZ4bGUrV2ZMYUlIb0NQNHFrT1pCWXB0dnlwTjhPWm56ZWc9PSIsIm1hYyI6IjU3NDJkNWE5M2U4YmIwNTUwNzhkZTM4ZTRlNDc5OTZhNjczYWEyODU0OGNmN2ViNDdkYTM4YjdjY2U1ZWE1ZmYifQ%3D%3D;
expires=Fri, 09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/,
laravel_session=zqcMrXeuwwGpEsR8Jh2WakDg0cdqLod4QsfMnfcd; expires=Fri,
09-Jun-2017 11:35:07 GMT; Max-Age=7200; path=/;
HttpOnly"],"access-control-allow-methods":["GET, POST, PUT, DELETE,
OPTIONS"],"access-control-allow-origin":["*"],"cache-control":["no-cache,
private"],"server":["Apache/2.4.18
(Ubuntu)"],"keep-alive":["timeout=5, max=100"],"date":["Fri, 09 Jun
2017 09:35:07
GMT"]}},"url":"http://no-tld/androidLogin","_bodyInit":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}","_bodyText":"{\"email\":\"chesterfield#gmail.com\",\"password\":\"123456\"}"}
I now want to access the returned email from my native-react app.
console.log(response.email); returns null. How can i access the returned email value in react native?
Try below fetch call,
React-native log-android //Android
or react-native log-ios // IOS
use to see response data or error details
fetch('http://no-tld.example/androidLogin', {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: 'chesterfield#gmail.com', password: '123456'})
}).then((response) => response.json())
.then((responseData) => {
console.log("responseData : " +responseData); // fetch response data
}).catch((error) => {
console.log("error : " +error); // error
});
I fixed it this way
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
try {
let response = await fetch('http://198.74.51.225/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'chesterfield#gmail.com',
password: '123456',
})
});
let res = await response.text();
if (response.status >= 200 && response.status < 300) {
let userData = JSON.parse(res);
console.log(userData.email);
} else {
//Handle error
// let error = res;
// throw error;
}
} catch(error) {
//console.log(res);
}
}
Just to be sure of the post data returned, you can modify the posted data in the server side and return it using this function
//Android Login
public function androidLogin(){
$rawData = file_get_contents("php://input");
$postedValue = json_decode($rawData,true);
$token = rand(400,7833);
return response()->json([
'email' => $token."_".$postedValue['email'],
'password' => $postedValue['password']
]);
}
For this to work, i had to also allow cors using this middleware
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
and i used it in my route like this
//Android
Route::group(['middleware' => ['cors']], function() {
Route::post('androidLogin', 'Auth\LoginController#androidLogin');
});
Hope that helps someone trying to post or get from a react-native app.