Network Error on formdata POST request React Native - javascript

I always get an Error: Network Error when trying to send a formData post request with axios. I tried to use fetch, xmlhttprequest, upgrade and downgrade axios/react-native... but no success. The thing is that sending the same content body on Insomnia/Postman returns a successful 200. Maybe it is something with the react-native way of creating/formatting a formData.
axios: 0.27.2
react-native: 0.64.2
react: 16.13.1
const sendAnswer = async () => {
if (!validateForm()) return false;
setPostLoading(true);
const body = new FormData();
const answersData = answers;
answersData.forEach((answerData) => {
const newAnswer = answerData;
const { tipo_dado: type, resposta: answer } = newAnswer;
if (type === 'imagem' || type === 'assinatura') {
body.append(newAnswer.sub_id, {
name: answer.name,
uri: answer.uri,
type: answer.type,
});
delete newAnswer.resposta;
}
return newAnswer;
});
body.append('formulario_id', formData._id);
body.append('respostas', answersData);
body.append('usuario_id', userData.id);
try {
const formResponse = await api.post(API_ANSWERS, body, {
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data;',
},
transformRequest: (data) => data,
});
} catch (error) {
console.log(error)
} finally {
setPostLoading(false);
}
};
edit: error object
{
"message": "Network Error",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformResponse": [
null
],
"timeout": 5000,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json",
"Content-Type": "multipart/form-data",
"Authorization": "secret_token_here"
},
"baseURL": "https://server.com.br",
"method": "post",
"url": "https://server.com.br/api-mobile/",
"data": {
"_parts": [
[
"6256b36ad1d2220009e9d6b1",
{
"name": "rn_image_picker_lib_temp_6dc1b2ae-f170-4f9a-b763-d4be94ccbcd7.jpg",
"uri": "file://data/user/0/br.com.rotaexata.rastreador/cache/rn_image_picker_lib_temp_6dc1b2ae-f170-4f9a-b763-d4be94ccbcd7.jpg",
"type": "image/jpeg"
}
],
[
"6256b36ad1d2220009e9d6b2",
{
"name": "image-1657132824768.png",
"uri": "file://data/user/0/br.com.rotaexata.rastreador/cache/image-1657132824768.png",
"type": "image/png"
}
],
[
"formulario_id",
"6256b36ad1d2220009e9d6b3"
],
[
"respostas",
[
{
"pergunta": "Qual a data?",
"tipo_dado": "data",
"options": [],
"obrigatorio": 0,
"sub_id": "6256b36ad1d2220009e9d6af",
"resposta": "2022-07-19"
},
{
"pergunta": "Qual o horário?",
"tipo_dado": "hora",
"options": [],
"obrigatorio": 0,
"sub_id": "6256b36ad1d2220009e9d6b0",
"resposta": "19:34"
},
{
"pergunta": "Insira uma imagem ",
"tipo_dado": "imagem",
"options": [],
"obrigatorio": 1,
"sub_id": "6256b36ad1d2220009e9d6b1"
},
{
"pergunta": "Assine por favor",
"tipo_dado": "assinatura",
"options": [],
"obrigatorio": 1,
"sub_id": "6256b36ad1d2220009e9d6b2"
}
]
],
[
"usuario_id",
26523
]
]
}
},
"code": "ERR_NETWORK",
"status": null
}
edit2: error response
{
"UNSENT": 0,
"OPENED": 1,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"DONE": 4,
"readyState": 4,
"status": 0,
"timeout": 5000,
"withCredentials": true,
"upload": {},
"_aborted": false,
"_hasError": true,
"_method": "POST",
"_perfKey": "network_XMLHttpRequest_1011",
"_response": "Unrecognized FormData part.",
"_url": "https://server.com.br/api-mobile/",
"_timedOut": false,
"_trackingName": 1011,
"_incrementalEvents": true,
"_performanceLogger": {
"_timespans": {
"network_XMLHttpRequest_1001": {
"startTime": 1493.8999999985099,
"endTime": 1701.8999999985099,
"totalTime": 208
},
"network_XMLHttpRequest_1002": {
"startTime": 1793,
"endTime": 3764.7999999970198,
"totalTime": 1971.7999999970198
},
"network_XMLHttpRequest_1003": {
"startTime": 1793.699999999255,
"endTime": 2188.5,
"totalTime": 394.80000000074506
},
"network_XMLHttpRequest_1004": {
"startTime": 1794.199999999255,
"endTime": 2632.7999999970198,
"totalTime": 838.5999999977648
},
"network_XMLHttpRequest_1005": {
"startTime": 1928.5,
"endTime": 2613.89999999851,
"totalTime": 685.3999999985099
},
"network_XMLHttpRequest_1006": {
"startTime": 2057.7999999970198,
"endTime": 2880.39999999851,
"totalTime": 822.6000000014901
},
"network_XMLHttpRequest_1007": {
"startTime": 4016.699999999255,
"endTime": 4833.199999999255,
"totalTime": 816.5
},
"network_XMLHttpRequest_1008": {
"startTime": 4017.099999997765,
"endTime": 4855.599999997765,
"totalTime": 838.5
},
"network_XMLHttpRequest_1009": {
"startTime": 4017.5,
"endTime": 4882.89999999851,
"totalTime": 865.3999999985099
},
"network_XMLHttpRequest_1010": {
"startTime": 9463.79999999702,
"endTime": 9774.199999999255,
"totalTime": 310.4000000022352
},
"network_XMLHttpRequest_1011": {
"startTime": 49170.599999997765
}
},
"_extras": {},
"_points": {
"initializeCore_start": 914.2999999970198,
"initializeCore_end": 935.2999999970198
},
"_pointExtras": {},
"_closed": false
},
"_requestId": null,
"_headers": {
"accept": "application/json",
"content-type": "multipart/form-data",
"authorization": "secret_token_here"
},
"_responseType": "",
"_sent": true,
"_lowerCaseResponseHeaders": {},
"_subscriptions": []
}

I solved it. This comment helped me.
When you want to append objects to the formData you need to convert them to JSON, so I converted the main array of objects with JSON.stringify(answersData)
body.append('formulario_id', formData._id);
body.append('respostas', JSON.stringify(answersData));
body.append('usuario_id', userData.id);

In react-native way of creating/formatting a formData works like everywhere.
Anyway let's try to check this:
If you make query to a remote server, make sure you use https format.
If you make query to a local server on android simulator try use "http:// 10.0.2.2:8000/" instead "http:// localhost:8000/" format.
And seems you did mistake in the row: 'Content-Type': 'multipart/form-data;', Try to remove semicolon.
If that won't help you, send me the full error object.

Related

How to upload file and array of objects with formdata in javascript to pass formdata in ajax

The output data are like the following params:
const treatementListe = {
"id": 0,
"date": "2021-10-22T09:41:19.678Z",
"selectedTraitements": "Injection1",
"selectedZones": "Face",
"traitementNote": "Careful",
"files": [
{
"upload": {
"progress": 100,
"total": 20261,
"bytesSent": 20261,
"filename": "1617826401810IMG-20210211-WA0002.jpg",
"chunked": false,
"totalChunkCount": 1
},
"status": "success",
"previewElement": {},
"previewTemplate": {},
...etc
}
]
},
{
"id": 1,
"date": "2021-10-22T09:41:19.678Z",
"selectedTraitements": "Injection2",
"selectedZones": "Ear",
"traitementNote": "Careful",
"files": [
{
"upload":{
"progress": 100,
"total": 20261,
"bytesSent": 20261,
"filename": "1617826401810IMG-20210211-WA0002.jpg",
"chunked": false,
"totalChunkCount": 1
},
"status": "success",
"previewElement": {},
"previewTemplate": {},
...etc
}
]
}

How do I parse the realtor api data to show property data (Realtor API/Rapid)?

’m trying to parse the response data to view property data. However, I searched through all the properties in the response data but none seemed to hold property data.
For anybody who isn’t familiar with realtor API this is the site I’m talking about. The data shows the exact way I want to receive mine
https://rapidapi.com/apidojo/api/realtor/endpoints
fetch("https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0", {
"method": "GET",
"headers": {
"x-rapidapi-host": "realtor.p.rapidapi.com",
"x-rapidapi-key": "e5b0286ea4msh1d616284115d5efp16cadcjsn0392ca0398ac"
}
})
.then(response => {
console.log(response.json());
})
.catch(err => {
console.log(err);
});
I was able to use Postman and test this endpoint and found that you likely need to be looking for the properties array and loop through the objects and sub-arrays/objects contained in each parent object of the properties array to get to the details about each property.
Inside of this array are objects that contain the address, latitude, longitude, etc.
I would recommend using Postman if you are not already, doing a GET request when doing so and using the same headers. You should see the same. Using Postman is a great way to test endpoints!
Here is an example of the data that is returned from the results inside of the properties array when hitting your endpoint with a GET request:
"properties": [
...
...
{
"property_id": "R3188507190",
"listing_id": "612930061",
"prop_type": "apartment",
"list_date": "2018-08-20T17:22:00.000Z",
"last_update": "2020-08-25T08:17:00.000Z",
"year_built": 2018,
"listing_status": "active",
"beds": 0,
"prop_status": "for_rent",
"address": {
"city": "Arverne",
"country": "USA",
"county": "Queens",
"lat": 40.589922,
"line": "190 Beach 69th St",
"postal_code": "11692",
"state_code": "NY",
"state": "New York",
"time_zone": "America/New_York",
"neighborhood_name": "Rockaway Peninsula",
"neighborhoods": [
{
"id": "8c06e34c-3044-5621-aea4-b59d9ddde719",
"level": "macro_neighborhood",
"name": "Rockaway Peninsula"
}
],
"lon": -73.79765
},
"client_display_flags": {
"presentation_status": "for_rent",
"is_showcase": true,
"lead_form_phone_required": true,
"price_change": 0,
"has_specials": false,
"is_mls_rental": false,
"is_rental_community": true,
"is_rental_unit": false,
"is_co_star": true,
"is_apartmentlist": false,
"suppress_map_pin": false,
"suppress_phone_call_lead_event": true,
"price_reduced": false,
"allows_cats": true,
"allows_dogs": true,
"allows_dogs_small": true,
"allows_dogs_large": true
},
"agents": [
{
"primary": true
}
],
"lead_forms": {
"form": {
"name": {
"required": true,
"minimum_character_count": 1
},
"email": {
"required": true,
"minimum_character_count": 5
},
"move_in_date": {
"required": true,
"default_date": "2020-09-01T12:00:00Z",
"minimum_days_from_today": 1,
"maximum_days_from_today": 180
},
"phone": {
"required": true,
"minimum_character_count": 10,
"maximum_character_count": 11
},
"message": {
"required": false,
"minimum_character_count": 0
},
"show": false
},
"show_agent": false,
"show_broker": false,
"show_provider": false,
"show_management": false
},
"lot_size": {
"size": 0,
"units": "sqft"
},
"building_size": {
"units": "sqft"
},
"rdc_web_url": "https://www.realtor.com/realestateandhomes-detail/190-Beach-69th-St_Arverne_NY_11692_M31885-07190",
"rdc_app_url": "move-rdc://www.realtor.com/realestateandhomes-detail/190-Beach-69th-St_Arverne_NY_11692_M31885-07190",
"community": {
"baths_max": 1,
"baths_min": 1,
"beds_max": 1,
"beds_min": 1,
"contact_number": "(844) 454-2289",
"id": 1839240,
"name": "The Tides At Arverne By The Sea",
"price_max": 2195,
"price_min": 2195,
"source_id": "46dfexj",
"sqft_max": 659,
"sqft_min": 659
},
"data_source_name": "co-star",
"source": "community",
"page_no": 1,
"rank": 1,
"list_tracking": "type|property|data|prop_id|3188507190|list_id|612930061|comm_id|1839240|page|rank|data_source|co-star|property_status|product_code|advantage_code^1|1|3K2|E8|0^^$0|1|2|$3|4|5|6|7|8|9|G|A|H|B|C|D|I|E|J|F|K]]",
"photo_count": 19,
"photos": [
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f75218736o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3178227471o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3306091863o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1799178643o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f884518299o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1142482343o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f624998745o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3641852832o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2581754924o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1976580515o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f586291969o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2803556443o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3294921843o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f852583007o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f4164216811o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3902720508o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f850731407o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2027588413o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f805760224o.jpg"
}
]
},
...
...
]
If the response is not returning the data you expect then it could be that the format of your fetch GET request code is not quite right.
EDIT: In fact, that is exactly the problem I do believe. So, it should probably work if you try to structure your fetch similarly to this:
let url = 'https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0';
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-rapidapi-host': 'realtor.p.rapidapi.com',
'x-rapidapi-key': 'e5b0286ea4msh1d616284115d5efp16cadcjsn0392ca0398ac'
}})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});

Angularjs $http is unable to get data from Asp.net webapi 4

I am trying to build an application with Asp.net web api and Angularjs
I am trying to get data from API but I am getting a null error as a result.
Asp.net web api code
[RoutePrefix("api/user")]
public class UserController : ApiController
{
[Route("login")]
[HttpGet]
public HttpResponseMessage login(string userId, string password)
{
...code to fetch data
return Request.CreateResponse(HttpStatusCode.OK, result);
}
web config
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
Angular Js Code
this.get = function (url, headers = {}) {
/// creating a defer
var def = $q.defer();
$http({
url: url,
dataType: 'json',
method: 'GET',
data: '',
headers: headers
}).success(function (data) {
def.resolve(data);
}).error(function (error) {
def.reject(error);
});
return def.promise;
};
Result
When I am trying to get the result by hitting the API URl I am getting error null
If I am opening the url in web browser then it is returning the JSON
Network Log
{
"log": {
"version": "1.2",
"creator": {
"name": "WebInspector",
"version": "537.36"
},
"pages": [],
"entries": [
{
"startedDateTime": "2016-06-02T16:27:59.550Z",
"time": 25.981999933719635,
"request": {
"method": "GET",
"url": "http://localhost:62158/api/user/login?userId=undefined&password=abc",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Origin",
"value": "http://localhost:8000"
},
{
"name": "Accept-Encoding",
"value": "gzip, deflate, sdch"
},
{
"name": "Host",
"value": "localhost:62158"
},
{
"name": "Accept-Language",
"value": "en-US,en;q=0.8,hi;q=0.6,und;q=0.4"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"
},
{
"name": "Accept",
"value": "application/json, text/plain, */*"
},
{
"name": "Referer",
"value": "http://localhost:8000/"
},
{
"name": "Connection",
"value": "keep-alive"
}
],
"queryString": [
{
"name": "userId",
"value": "undefined"
},
{
"name": "password",
"value": "abc"
}
],
"cookies": [],
"headersSize": 429,
"bodySize": 0
},
"response": {
"status": 200,
"statusText": "OK",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Pragma",
"value": "no-cache"
},
{
"name": "Date",
"value": "Thu, 02 Jun 2016 16:27:59 GMT"
},
{
"name": "Server",
"value": "Microsoft-IIS/8.0"
},
{
"name": "X-AspNet-Version",
"value": "4.0.30319"
},
{
"name": "X-Powered-By",
"value": "ASP.NET"
},
{
"name": "Content-Type",
"value": "application/json; charset=utf-8"
},
{
"name": "Cache-Control",
"value": "no-cache"
},
{
"name": "X-SourceFiles",
"value": "=?UTF-8?B?QzpcVXNlcnNca2lyXERlc2t0b3BcRSBEcml2ZVxXb3JrIExpdmVcTml0aW4gS0sgU29mdHdhcmVcVmlkZW9MaWJyYXJ5XHByb2plY3RcVmlkZW9MSWJyYXJ5XFZpZGVvTElicmFyeVxhcGlcdXNlclxsb2dpbg==?="
},
{
"name": "Content-Length",
"value": "46"
},
{
"name": "Expires",
"value": "-1"
}
],
"cookies": [],
"content": {
"size": 0,
"mimeType": "application/json",
"compression": 447,
"text": ""
},
"redirectURL": "",
"headersSize": 447,
"bodySize": -447,
"_transferSize": 0,
"_error": ""
},
"cache": {},
"timings": {
"blocked": 2.24999990314245,
"dns": -1,
"connect": -1,
"send": 0.19500008784235012,
"wait": 22.8659999556839,
"receive": 0.6709999870509336,
"ssl": -1
},
"serverIPAddress": "[::1]",
"connection": "15008"
}
]
}
}
Same Hit in browser giving result
As KKKKKKKK and rick have already pointed out you don't need to create another promise as $http.get will already return one. You should also make use of then as opposed to succcess/failure
So what you want should look like this:
function getData() {
return $http.get('path-to-api/api.json').then(
function success(result) {
// Do stuff with it
return result.data;
},
function failure(err) {
return err;
});
}
Note this places the call in a service and returns the function in an object from that service.
EDIT
Because the comments concates URLS I'll add this as an edit:
So the url you're hitting on the angular side is:
http://localhost:62158/api/user/login?userId=undefined&password=abc.json
or is http://localhost:62158/api/user/login?userId=undefined&password=abc
#Katana24 I do not know how to thank you but you made me get this answer... thanks a lot.
Reason
Asp.net web api does not allow cross origin request until and unless you add Access-Control-Allow-Origin in web.config file. I made it * so from any origin the APIes is accessible.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>

Create Recurring Outlook Calendar Event using Node.js

I am trying to create Recurring event using Outlook Rest API in node.js for that I gone through documents whcihis provided by Microsoft but there is no sample example found ,but I am getting error as
{
"error": {
"code": "RequestBodyRead",
"message": "An unexpected 'PrimitiveValue' node was found when reading from the JSON reader. A 'StartObject' node was expected."
}
}
My Code:
var jsonBody = {
"Subject": "test event",
"Body": {
"ContentType": "HTML",
"Content": "sadsad"
},
"Start": "2016-05-27T00:00:00.000Z",
"End": "2016-05-27T00:30:00.000Z",
"Attendees": result,
"Type":"Occurrence",
"Recurrence": {
"Pattern": {
"DayOfMonth": 0,
"Month": 0,
"Type": "Daily",
"Interval": 3,
"FirstDayOfWeek": "Sunday"
},
"Range": {
"StartDate": "2015-05-27T00:00:00Z",
"EndDate": "0001-01-01T00:00:00Z",
"NumberOfOccurrences": 0,
"Type": "NoEnd"
}
}
};
var optionsForCreatingcalendar = {
uri: 'https://outlook.office.com/api/v2.0/me/events',
port: 443,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
},
json: true,
body: jsonBody,
resolveWithFullResponse: true,
simple: false
};
// --- API call using promise-----
rp(optionsForCreatingcalendar)
.then(function(response) {
},function(err){
});
Can some one help me resolve it?
Thanks in Adavnce.
Thank god,I solved my problem.Because of Date format I was not able to create Event.
Working Code:
var jsonBody = {
"Subject": "test event",
"Body": {
"ContentType": "HTML",
"Content": "sadsad"
},
"Start": {
"DateTime": "2016-05-21T10:10:00",
"TimeZone":"India Standard Time"
},
"End": {
"DateTime":"2016-05-21T11:10:00",
"TimeZone":"India Standard Time"
},
"Attendees": result,
"Type":"Occurrence",
"Recurrence": {
"Pattern": {
"DayOfMonth": 0,
"Month": 0,
"Type": "Daily",
"Interval": 3,
"FirstDayOfWeek": "Sunday"
},
"Range": {
"StartDate": "2016-05-27",
"EndDate": "2016-06-27",
"NumberOfOccurrences": 0,
"Type": "NoEnd"
}
}
};
Thank you All.

Loopback external api errors

I have created my external api on loopback, i tried to use the Model.find method and other query methods, it not working for me, what i get is just error message.
Below are the message i get
the error i get
After i check it might be my api result problem, because my object is inside another object.
my api output
Can some guide me how to solve it, can change the output result?
datasources.js
"consumer_model": {
"name": "consumer_model",
"connector": "rest",
"debug": "false",
"operations": [
{
"template": {
"method": "GET",
"url": "http://myurl.com/api/v1/consumers",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
},
"query": {
"id": "{id}",
"firstname": "{firstname}"
},
"responsePath": "$.data"
},
"functions": {
"consumer": [
"id",
"firstname"
]
}
}
]
}
model-config.js
"consumers": {
"dataSource": "consumer_model",
"public": true
}
myconsumer.js
module.exports = function(consumers) {
};
myconsumer.json
{
"name": "consumers",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

Categories

Resources