I have read many questions similar to mine but none solved my issue,
my fetch (Get Method) is working fine but the (POST METHOD) shows Unexpected end of JSON input
fetch('http://monasabat-app.com/Queries/sub_cat.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: 3
}),
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
fsubCategory: responseJson.sub_cat
})
})
.catch((error) => {
console.error(error);
});
}
And this is the response I got by POSTMAN
{
"sub_cat": [
{
"id": "4",
"sub_cat": "sbu1",
"img_path": "url"
},
{
"id": "9",
"sub_cat": "sub2",
"img_path": "url"
}
]
}
Even if you try in postMan using Content-Type: application/json you will notice you don't get any response.
POST /Queries/sub_cat.php HTTP/1.1
Host: monasabat-app.com
Accept: application/json
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: c60774f8-1aaa-4cf8-8aa3-abcab34b05e3
{id:3}
The unexpected end of JSON input it's because it's trying to parse an empty string.
So it's not an issue related to fetch, just try the following to get the proper response:
fetch('http://monasabat-app.com/Queries/sub_cat.php', {
method: 'POST',
headers: {
'Content-Type':'application/x-www-form-urlencoded',
},
body: 'id=3',
})
Related
Problem: Postman and Axios Error Messages are different, and I'd like to know how I can get the same error message in Axios as Postman gets.
Postman Error body:
{ "message": "Internal Error. Details are available in Magento log file. Report ID: webapi-xxxxxxxxxxxxx" }
Error status provided: 500 Internal Server Error
Axios Error Body:
{
message: 'Request failed with status code 500',
name: 'AxiosError',
stack: 'AxiosError: Request failed with status code 500\n' +
' at settle (/var/task/node_modules/axios/dist/node/axios.cjs:1261:12)\n' +
' at IncomingMessage.handleStreamEnd (/var/task/node_modules/axios/dist/node/axios.cjs:2444:11)\n' +
' at IncomingMessage.emit (node:events:539:35)\n' +
' at endReadableNT (node:internal/streams/readable:1345:12)\n' +
' at processTicksAndRejections (node:internal/process/task_queues:83:21)',
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
transformRequest: [ null ],
transformResponse: [ null ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { Blob: null },
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
Authorization: 'OAuth oauth_consumer_key="XXXXXXXXXXXXXX",oauth_token="XXXXXXXXXXXXXX",oauth_signature_method="XXXXXXXXXXXXXX",oauth_timestamp="XXXXXXXXXXXXXX",oauth_nonce="XXXXXXXXXXXXXX",oauth_version="1.0",oauth_signature="XXXXXXXXXXXXXX="',
Cookie: 'XXXXXXXXXXXXXX=XXXXXXXXXXXXXX',
'User-Agent': 'axios/1.1.2',
'Content-Length': '1094',
'Accept-Encoding': 'gzip, deflate, br'
},
method: 'post',
url: 'XXXXXXXXXXXXXX',
params: {},
data: "XXXXXXXXXXXXXX",
'axios-retry': { retryCount: 0, lastRequestTime: 1676022167464 }
},
code: 'ERR_BAD_RESPONSE',
status: 500
}
It is evident the "Details are available in Magento" is not showing in the Axios Error. Why is that?
I would like to create simple apps that make user can post data to json.
Here is my code.
componentDidMount = () => {
fetch('https://site.json',
{
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example'
})
}
).then(response => response.json()).then(data => console.log(data))
.catch(err => console.log("api Erorr: ", err));
}
But finally, I get an error api Erorr: [TypeError: Network request failed]
Is it Cors block my access???
Any idea how to solve it, Thank you very much
There is something wrong with the URL. The same code working fine with other urls like.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
value: 'React POST Request Example',
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log('api Erorr: ', err));
}}
If I do this in PostMan, I get a response back which I can toggle html and json, but in my react native app I'm getting a console error of JSON Parse Error: Unexpected EOF
I have the content type of my sent header as x-www-form-urlencoded because that was the only way to get my proper response even on postman.
I have my backend in wordpress sending a response array as json_encoded (echo json_encode($response)) and I can get it by url and post man, but my app just can't get past this unexpected EOF and I think it has to do with my .then statements
WHat am I doing wrong here?
validate(){
const {navigate} = this.props.navigation;
this.setState({ validating: true });
let formData = new FormData();
formData.append('type', 'login');
formData.append('email', this.state.email);
formData.append('password', this.state.password);
return fetch('https:/site/authentication.php', {
method: 'POST',
body: JSON.stringify(formData),
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
return data;
})
.catch(function(err) {
console.log(err);
})
}
Looking at your response:
Response { "_bodyBlob": Blob { "_data": Object { "blobId": "31418cda-5d2e-4ee0-8c67-626e7ebe0502", "offset": 0, "size": 0, }, }, "headers": Headers { "map": Object { "cache-control": "public, max-age=0", "content-length": "0", "content-type": "text/html; charset=UTF-8", }, }, "ok": true, "status": 200, "statusText": undefined, "type": "default", "url": "https://site/authentication.php", } Promise { "_40": 0, "_55": null, "_65": 0, "_72": null, }
I think it is a blob not JSON. Try and use this instead:
.then(response => response.blob())
Sorry I missed that earlier.
Blob MDN Ref: response.blob()
I'm trying to fetch from an API, using an API key, but keep getting 406 Not Acceptable.
I can get the request to work in Postman, but not in the code. What could be wrong here? I've tried all sorts of ways of including my info in headers, this is just my last attempt.
componentDidMount() {
fetch("my-api", {
method: "GET",
headers: ({
Accept: "application/json",
"Content-Type": "application/json",
"X-Api-Version": 20161108,
Authorization: {
Token: "my-api-key",
}
}),
body: JSON.stringify()
}).then(response => {
if (response.status === 201) {
console.log(response)
return response.json()
} else {
console.log("oh no!", response.status === 404)
}
})
}
I figured it out. This ended up working:
componentDidMount() {
fetch("my api", {
method: "GET",
headers: ({
Accept: "application/vnd.api+json",
"Content-Type": "application/json",
"X-Api-Version": 20161108,
Authorization: "Token my token",
}),
body: JSON.stringify()
}).then(response => {
if (response.status === 200) {
console.log(response)
return response.json()
} else {
console.log("oh no!", response.status === 404)
}
})
}
I'm getting a serialized JSON body from our API like the below example: '
{
"_embedded": [
{
"id": 1,
"vulnerable": false,
"systemId": "something",
"friendlyName": "a friendly name"
},
]
}
How to show just the key/value friendlyName? I'm using axios to get the response. This is my code:
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
transformResponse: axios.defaults.transformResponse.concat((data) => {
console.log(data) // this should now be JSON
})
}).then(({ data })=> {
this.setState({
data: houses.friendlyName
});
})
.catch((err)=> {
console.log(err);
});
I think I'm supposed to transform the data, but I don't know how. Thanks for any help.
Edit: This is how the response is shown in console:
_embedded:
0:
friendlyName: "a friendly name"
id: 1
systemId: "GE8BP2IACH7"
vulnerable: false
So, how do I deserialize it?
axios.get(BASE_URL + 'household/list',{
headers: { Authorization: AuthStr },
}).then(function (response) {
this.setState({data:response._embedded.friendlyName})
})
.catch(function (error) {
console.log(error);
});