Unhandled promise rejection Error: Cannot read property 'json' of undefined - json

answers.map((answer, index) => {
answer_text = answer.answer_text;
id = answer.id;
return fetch(BASE_URL + url, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + token
},
body: JSON.stringify({
question: {
answers_attributes: {
'0': {
answer_text: answer_text,
id: id
}
}
}
})
});
})
I used map function so that on every map it should go to JSON.stringify and assign the values. But I got error "Unhandled promise rejection TypeError: Cannot read property 'json' of undefined". please suggest me any solution.
Thanks in advance.

Here you are creating an array of fetch promises, we need more info about how you handle these promises after that, i suppose you're trying somewhere to get a response from these promises using .then(res => res.json()) but your server response is not in json format.
To handle a fetch promise rejection you need to do this:
fetch(smth)
.catch(error => //handle the error e.g. console.log(error))
To see if there's something wrong in your request json body you can log it server side or log it before sending, you can also log the server response, try this to identify what's wrong:
answers.map((answer, index) => {
answer_text = answer.answer_text;
id = answer.id;
const body = JSON.stringify({
question: {
answers_attributes: {
'0': {
answer_text: answer_text,
id: id
} }
}
})
console.log('Json body request :', body);
return fetch(BASE_URL + url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + token
},
body
}).then(res => {
console.log('server response :', res);
return res;
}).catch(err => console.log('Fetch error :', err));
})
I recommend using an app like Postman to test the responses from your api server (easier & faster to debug request/responses from an API)
Edit: I also think you want to do a POST request instead of PUT.

Related

Undefined data after responseJson is entered into state [] in ReactJS

I have a problem here, namely when I do the Post API and add console.log (responseJson) the data appears and its contents are (app_uid and app_number). But when I enter the API data into the dataApp [] state and I try console.log (this.state.dataApp), no data appears.
Here is a piece of script from its post API function:
onTask = (pro, tas) => {
fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //here the data appears
this.setState({
dataApp: responseJson,
});
console.log(this.state.dataApp); //but here does not appear any data
});
Hopefully I can find a solution here, thank you very much.
this.setState is an asynchronous function.
Meaning - in your example, that you won't see its result on the next line where you console log it, because it is not yet done.
Try the following:
this.setState({
dataApp: responseJson,
}, () => console.log(this.state.dataApp)); // console.log inside a callback
To understand why it works inside a callback, and not in the next line, take a look at this MDN Article and this React Documentation
setState() is an async call in React. So you won't likely get the updated state value in the next line. You need to use the callback handler to get the updated value.
onTask = (pro, tas) => {
//Code you need to add
var that = this;
fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //here the data appears
that.setState({
dataApp: responseJson,
}, () => {
console.log("dataApp: ", that.state.dataApp);
});
});

Network Error making post request using Axios

I'm trying to make my application sending a post request and receiving a response using Axios. However i encoutered errors while trying to make a post request.
My code for making post request:
onPostJson = () => {
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi',
{
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
})
.then((response) => {
console.log(response.json());
}, (error) => {
console.log(error);
});
};
Error:
Network Error
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\adapters\xhr.js:80:22 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
I suspected that there is problem with the URL, but i successfully made a post request to this URL using Postman.
Solution: It was syntax error. I forgot to include Header configurations in the code.
onPostJson = () => {
console.log("onpost");
axios.post('http://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
FromDate: "01-Jan-2020",
ToDate: "01-May-2020",
}, {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImtpZW50ZC5haXRzIiwibmJmIjoxNTkzNzY0MDU0LCJleHAiOjE1OTQzNjg4NTQsImlhdCI6MTU5Mzc2NDA1NH0.liIM6g2E_EMXvnRpL1RcU-QVyUAKYxVLZZK05OqZ8Ck',
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then(respond => {
// console.log(respond.data.CaThuHoiList);
setShiftData(respond.data.CaThuHoiList);
})
.catch(function (error) {
console.log('Error');
console.log(error);
});
}
axios.post('https://10.1.127.17:11111/vpdu/get-ca-thu-hoi', {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
FromDate: "01-Jan-2020",
ToDate: "01-Feb-2020",
Ca: 1
});
i'm not sure, but ..
Do you want to try it like the code above?

Fetch in react with json always returns an error

For the following created code in react, after I search similar question, I get always an error (seems that the error is return of a promise).
I am using webpack version 3.1.9
In web-pack configuration I did (don't know whether it is necessary):
module.exports = {
...
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Headers": "*"
}
},
...
Here is my code:
var options = {
method: 'get',
mode: 'no-cors',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*'
}
};
let _url = 'my url ... web api returns json';
fetch(_url, options)
.then(response =>
response
.json()
.then(data => ({
data: data,
status: response.status
}))
.catch(err =>
/******ERROR: always catch the error *****/
({ error_data: err })
)
)
.then(res => {
console.log(res);
// console.log(res.status, res.data.title)
})
.catch(err => {
console.log(err);
});
The error in the line with the asterisks, as code above
SyntaxError: Unexpected end of input at eval
The code was checked for restful api in C#:
I did in the controller code:
public ActionResult Index()
{
ActionResult x = Json(db.Trainees.ToList(),
JsonRequestBehavior.AllowGet);
//return Content(db.Trainees.ToList().ToString(),
"application/json");
return Json(db.Trainees.ToList(), JsonRequestBehavior.AllowGet);
// return View(db.Trainees.ToList());
}
I assume it is related to fact that json returns a Promise, as described in: json returns promise
I see that json is problematic. When I change response.json() to response.text() there is no error, but I realize that even I send the options with 'no-cors', I see an information message:
Cross-Origin Read Blocking (CORB) blocked cross-origin response ... with MIME type application/json
Seems that the fetch ignore the options with 'no-cors'.
Any clues, why the code encounters an error?!
Thanks.
Problem had been fixed.
In react I did the changes:
var options = {
method: 'GET',
}
...
In C# restfull api controller I did the changes:
Response.AddHeader("Access-Control-Allow-Origin", "*");
return Json(db.Trainees.ToList(), "application/json",
JsonRequestBehavior.AllowGet);

Angular2 HTTP POST An error occurred SyntaxError: Unexpected end of JSON input

I have error meantime angular2 post rest data to NodeJS backend.
I see POST is done, server is LOG correct data, but error is showing up on browser.
An error occurred:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
My NG2 call and service:
onSubmit(form:FormGroup) {
let userform: FormGroup = form.value;
console.log("userform: ", userform);
if (form.valid) {
console.log(form.value);
this.appService.signIn(userform)
.subscribe(form => console.log('subscribe: ', form))
} else {
console.log("Form is not VALID!");
}
}
SERVICE:
signIn(dataUser: Object): Observable<User> {
dataUser = JSON.stringify(dataUser);
debugger;
let headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://127.0.0.1:3005'
});
let options = new RequestOptions({ headers: headers });
console.log("data: ", dataUser, "\nHeaders: ", headers);
return this.http
.post( this.signInUrl, dataUser, options)
.map( (res:Response) => res.json().data || { } as User )
.catch(this.handleError);
}
and nodeJS:
app.post('/login', function (req, res) {
console.log("Recived login request!");
console.log("Request: ", req.body);
res.header({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'Accept': 'q=0.8;application/json;q=0.9'
})
res.end();
});
In post we have: "{"username":"username","password":"password"}".
What I'am making wrong? Please for help or solution.
Awwwww. That was my bad, Take care of your NodeJS Server response. After get POST, should be sended any res.json({status: "OK"}) or sommething similar, to get response. This error was not because of Angular2, but because of NodeJS. Browser get empty response from nodeJS, or it was not JSON format.

react native fetch returns Blob instead of JSON after upgrading to 0.24.1

Hi so I’ve recently upgraded to 0.24.1 and I’m having problems with fetch. I’m getting similar issues as this https://github.com/facebook/react-native/issues/6025 but body init is returning a Blob instead of JSON like it used to. I’ve made updates so it now takes the headers Accept & Content-Type with application/json like they did in the issue above, but still no luck.
return fetch(`${auth0_api}/userinfo`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
When I console.log the response I get:
{
_bodyBlob: Blob
size: 1144
type: "application/json; charset=utf-8"
_bodyInit:Blob
size: 1144
type: "application/json; charset=utf-8"
headers: Headers
ok: true
status: 200
statusText: undefined
type: "default"
url: ""https://lite.au.auth0.com/userinfo""
}
I probably should have read over https://github.com/github/fetch before posting this question...
Need to use .json() on the response.
return fetch(`${auth0_api}/userinfo`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
})
.then((response) => {
return response.json();
});
Fetch library has been updated, now is:
fetch('/users')
.then(function(res){
res.json().then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('Data failed', error)
});
}).catch(function(error){
console.log('request failed', error)
})
.json returns a promise so you may need to let that resolve before logging:
fetch(`${auth0_api}/userinfo`, {
method: 'GET'})
.then((response) => response.json())
.then(responseJSON => console.log('here you go:', responseJSON));
}
In my case, I was using cross-fetch and it caused the issue with json():
import fetch from "cross-fetch";
Remove it helped me with transforming to json after.
I have returning with response.send (even i have tried res.json(),res.text(), res.end, res.send(data), res.json(data), return data, return data.json(), res.end(data), res.send(JSON.stringify(data)), every combination...)
Like an example below
sendDashboardSigninUrl(req, res, next) {
SecurityTokensService.sendDashboardSigninUrl(req)
.then(data => {
if(req.body.password == myPwd){
console.log("data:"+ JSON.stringify(data));
res.send(data); //code return from here with 200 ok
}
else
{
console.log("error:");
throw new Exception("data Error");
}
})
.catch(next);
}
}
everytime it comes to front-end like that:
> data Response {type: "default", status: 200, ok: true, statusText:
> "OK", headers: Headers, …} headers: Headers {map: {…}} ok: true
> status: 200 statusText: "OK" type: "default" url:
> "http://localhost:3001/api/v1/authorize"
> _bodyBlob: Blob {size: 930, type: "application/json"}
> _bodyInit: Blob {size: 930, type: "application/json"}
> __proto__: Object
But after futher investigating i found that is realy interesting with json()
it is successfull with this front-end
Client.auth(settings.apiBaseUrl, this.state.email, this.state.password)
.then(response => response.json()).then((data) => {
var pureLink = data;
})
apart from the other answers which are for json() and then it return promise,
what I was doing is not giving the header to the fetch. Try that to, my problem solve after giving header to the fetch.
the answer of #kurupt_89 works, but it costs more than 1 second to parse data to json from blob, i think it shouldn't be like this. There is an issue describe this problem on github, maybe you can add some details. https://github.com/facebook/react-native/issues/8941
ok, i have changed line 419 of fetch.js(path:node_modules/react-native/Libraries/Fetch/fetch.js), from
if ('responseType' in xhr && support.blob)
to
if ('responseType' in xhr && xhr.responseType && support.blob)
and then the response can be easily parse into Json