ReactJS - unable to fetch from API - javascript

So what I am trying to do is do send some data by clicking a submit button (A mathematical expression) to a Django-API. There this expression is processed and a new expression is returned to another textbox. I am trying to do this in a single function. The Post requests are working perfectly fine which I have checked through the Postman application.
I am unable to fetch the processed data from the API. I am getting the following error -->
GET http://127.0.0.1:8000/differentiate/ 405 (Method Not Allowed)
The overview of the application -->
The code for my function is ->
async postData() {
const url = 'http://127.0.0.1:8000/differentiate/';
let result = await fetch(url,{
method: 'post',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
functiondata: this.fx
})
});
fetch(url).then(res => res.json()).then(json => {
this.setState({
fprimex: JSON.stringify(json)
})
})
};

Related

`POST` request to script page

The function below is contained in the Apps Script code.gs file:
function doPost(e) {
if(typeof e !== 'undefined')
return ContentService.createTextOutput(JSON.stringify(e.parameter));
}
If I make a request using fetch from the background.js of my Chrome extension and include the id parameter in the URL, I get the expected result.
const url = 'https://script.google.com/.../exec?id=123';
fetch(url)
.then(response => response.text())
.then(data => { console.log(data) }) // {"id":"123"}
Instead of writing id as a parameter in the URL, I would like to make the request using the POST method.
I tried to use the object below, but I don't know how to include the variable I want to send:
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: {}
}
I believe your goal is as follows.
You want to send the value of id=123 with the request body instead of the query parameter.
In this case, how about the following modification?
Google Apps Script side:
function doPost(e) {
if (typeof e !== 'undefined') {
const value = JSON.parse(e.postData.contents); // This is the value from the request body.
return ContentService.createTextOutput(JSON.stringify(value));
}
}
Javascript side:
const url = "https://script.google.com/macros/s/###/exec";
const data = { id: 123 };
fetch(url, { method: "POST", body: JSON.stringify(data) })
.then((res) => res.text())
.then((res) => console.log(res));
By this modification, you can see the value of {"id":123} in the console.
Note:
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script (Author: me)
To include the data you want to send in the request body and to make a POST request using the fetch function, you can do the following:
const data = {id: '123'};
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.text())
.then(data => { console.log(data) })
This send a POST request to the URL with data in the request body. The server-side function (in this case, doPost) will receive the data in the e.parameter object.
I hope this helps you.

Why can't I send a form data from axios?

I am consuming an api that asks me to send a filter series within a formData, when doing the tests from Postman everything works without problem, I tried with other libraries and it also works without problem, but when trying to do it from axios the information does not return with the filters.
This is the code I am using:
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'get',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});
You can send Form-data using get method, but the most servers, will reject the form data.
However it is not recommended anymore. The reason is, first because it is visible in the URL and browsers can cache them in it’s history backstacks, and second reason is because browsers have some limitations over the maximum number of characters in url.
If you are to send only few fields/input in the forms you can use it but if you have multiple inputs you should avoid it and use POST instead.
At the end it depends on your own usecase. Technically both GET and POST are fine to send data to server.
replace get with post
const axios = require('axios');
const FormData = require('form-data');
let data = new FormData();
data.append('filtro_grafica', '2,0,0,0');
let config = {
method: 'post',
url: 'https://thisismyurl/filter',
headers: {
'Authorization': 'JWT MYTOKEN',
...data.getHeaders()
},
data : data
};
axios(config)
.then((response) => {
console.log(JSON.stringify(response.data));
})
.catch((error) => {
console.log(error);
});

Unable to send objects as payload data while making an Fetch API request

I have a react frontend and node backend, I am fetching a list of objects from an external API using Axios and then trying to pass it to my node backend. The issue is that the node backend is not able to receive this payload data on the backend, req.body returns an empty object.
To debug, I've seen what happens in the network tab, and have observed that the payload data just returns the data type instead of the actual data as shown below.
enter image description here
Here is what my front-end code looks like:
let faqlist = "";
// fetching data from one api
await axiosinstance
.get(
"https://linktotheapi/api/faq"
)
.then((res) => {
faqlist = res.data;
console.log("This is faqlist", faqlist);
console.log(typeof faqlist);
// passing the data fetched from 1st api to node/express backend.
fetch("/create-page", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: faqlist,
});
});}
You can stringify the array of objects before sending. Use JSON.stringify
const x = [{ x: 1 }, { x: 2 }];
fetch("https://httpbin.org/post", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(x)
});

React Native - Fetch POST not working

I am having huge troubles getting my fetch POST calls to work on iOS. My standard Fetch calls work and the Fetch POST calls work fine on android but not iOS.
The error that comes up is "Possible Unhandled Promise Rejection (id: 0): Unexpected token < in JSON at position 0"
It actually saves the post data to my server but throws that error.
I tried debugging the network request using GLOBAL.XMLHttpRequest = GLOBAL.originalXMLHttpRequest || GLOBAL.XMLHttpRequest; before the API call coupled with using CORS in my chrome debug tools. From there I can see that it is making two post calls one after the other. The first one has type "OPTIONS" while the second one has type "POST". It should probably be noted that the call works in the App while using CORS and the line of code above.
I'm very confused and have exhausted all avenues.
My code im using for refrence is as follows.
return fetch(url,{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then((res) => res.json());
If JSON.stringify is not working, then try to use FormData.
import FormData from 'FormData';
var formData = new FormData();
formData.append('key1', 'value');
formData.append('key2', 'value');
let postData = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
}
fetch(api_url, postData)
.then((response) => response.json())
.then((responseJson) => { console.log('response:', responseJson); })
.catch((error) => { console.error(error); });
You use the following code for POST request in react native easily. You need to only
replace the parameter name and value and your URL only.
var details = {
'userName': 'test#gmail.com',
'password': 'Password!',
'grant_type': 'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch('http://identity.azurewebsites.net' + '/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formBody
}).
.then((response) => response.json())
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
Alert.alert('problem while adding data');
})
.done();
I would guess the response you are receiving is in HTML. Try:
console.warn(xhr.responseText)
Then look at the response.
Also, IOS requires HTTPS.
Edit: Possible duplicate: "SyntaxError: Unexpected token < in JSON at position 0" in React App
Here is an example with date that works for me!
The trick was the "=" equal and "&" sign and has to be in a string format in the body object.
Find a way to create that string and pass it to the body.
====================================
fetch('/auth/newdate/', {
method: 'POST',
mode: 'cors',
redirect: 'follow',
body: "start="+start.toLocaleString()+"&end="+end.toLocaleString()+"",
headers: new Headers({
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
})
}).then(function(response) {
/* handle response */
if(response.ok) {
response.json().then(function(json) {
let releasedate = json;
//sucess do something with places
console.log(releasedate);
});
} else {
console.log('Network failed with response ' + response.status + ': ' + response.statusText);
}
}).catch(function(resp){ console.log(resp) });
server node.js?
npm i cors --save
var cors = require('cors');
app.use(cors());
res.header("Access-Control-Allow-Origin: *");

Javascript fetch response cutoff

I'm starting to learn react-native and ran into some problems while using fetch on Android.
try {
let response = await fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
***parameters***
})
});
let responseJson = await response;
if(responseJson){
// console.log(responseJson);
console.log(responseJson.text());
// console.log(responseJson.json());
}
} catch(error) {
console.error(error);
}
The request is sent correctly but the answer isn't shown in it's totality:
(**loads more data before**){"ID":"779","DESCRICAO":"ZXCVB","CLIENTENUMERO":"10133","CLIENTENOME":"Lda 1","TREGISTO":"2015\\/11\\/24 09:34:15","TTERMO":"","SITUACAO":"C","TIPO":"P","NOTIFICACOES":"email","NOTIFI_TAREFA":"","ESFORCOS_TOT":"4","TEMPOGASTO_TOT":"0:01:44","TEMPOGASTO_PES":"0:01:44","PROJECTO":"New Products","USERNAME":"AT","UREGISTO":"S","EMCURSO":"0","TULTIMO":"2015\\/12\\/18 20:37:56","EQUIPA":"","NIVEL":"AVISAX"},{"ID":"783","DESCRICAO":"123","CLIENTENUMERO":"10133","CLIENTENOME":"Lda 1","TREGISTO":"2015\\/11\\/24 09:43:26","TTERMO":"","SITUACAO":"C","TIPO":"P","NOTIFICAC
As you can see, the JSON object isn't complete. Sending the same request using other methods in a browser returns the JSON correctly.
I'm wondering if this is an actual issue with fetch or with Android.
I've tried setting size and timeout parameters to 0 in fetch but it did nothing.
Edit: also tried using synchronous fetch instead of async, with the same effect:
fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
***params***
})
})
.then((response) => response.text())
.then((responseText) => {
console.log(responseText);
})
.catch((error) => {
console.warn(error);
}
Also tried:
console.log(responseJson);
and
console.log(responseJson.json());
Edit for further clarification:
When using response.json(), the response is shown as json (as to be expected) but it's still incomplete.
Edit :: Issue was with console.log limiting the number of characters it displays in the console.
Quick question:
Can you get the json object in its entirety if you hit the endpoint with postman? It could very well be your server/service that is cutting off the message.
Lastly, (and I see you mentioned this above) but I always use the 'json' method off the response obj when I know that is the notation type - which should return a promise.
fetch(REQUEST_URL, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
***params***
})
})
//get the response and execute .json
.then((r) => r.json())
//then listen for the json promise
.then((j) => {
console.log(j);
})
.catch((error) => {
console.warn(error);
}
Let me know what happens and if you get the full response with postman (or fiddler compose).

Categories

Resources