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);
});
Related
the parameter with attribute named file is required and the actual curl command is:- curl -F "file=#password.txt" https://safenote.co/api/file -F password=secret -F lifetime=72 and the corresponding json format is:-
{
"url": "https://safenote.co/api/file",
"raw_url": "https://safenote.co/api/file",
"method": "post",
"files": {
"file": "password.txt"
},
"data": {
"password": "secret",
"lifetime": "72"
}
}
I need this to be converted into a fetch function or using axios, I'm not understanding which is the body part ad what to include
I have tried :-
fetch(`https://safenote.co/api/file`,{
mode:'no-cors',
method:"POST",
// headers: {
// "Content-Type": "application/json"
// },
"files":{
"file":selectedFile,
},
// body: JSON.stringify({
// file:selectedFile
})
// })
.then(response => response.json())
.then(data => console.log("data",data))
.catch(error => console.log(error));
}
my HTML part
<input type="file" name="attachment" accept="image/png, image/jpeg" onChange={(e) => setSelectedFile(e.target.files[0])}/>```
You can use axios and form data for that
const myFormData = new FormData();
myFormData.append('files', 'file');
You can add another properties like name or whatever too
myFormData.append('name', 'myFileName');
then use the axios
axios({
method: "post",
url: "myurl",
data: myFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
I am trying to make a Post request to an api but for some reason i am getting a 400 feedback in the process. Being that i am a beginner at this, i can't really figure out where i am getting it wrong. I understand 400 error has to do with incorrect syntax but i am not sure that is the case here. I also checked out the other related posts but none helped address my problem. I have also read through the documentation over and over again but still can't see where i am making a mistake. I will appreciate if you helped me point out the problem.
myPostRequest(){
var mybody = {
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN","partyId": "0977948551"}
}
mybody = JSON.stringify(mybody);
var token = "mytoken";
//POST request
fetch('https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay', {
method: "POST",
headers: {
'Authorization': 'Bearer '+token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
},
body: mybody,
})
.then((responseJson) => {
alert(JSON.stringify(responseJson));
console.log(responseJson);
})
.catch((error) => {
alert(JSON.stringify(error));
console.error(error);
});
}
Use axios/apisauce instead of fetch
apisauce example:
import { create } from 'apisauce';
const api = create({
baseURL: `http://example.com`,
});
const response = await api.post('/path/to/', body, { headers });
In your case:
import { create } from 'apisauce';
const api = create({
baseURL: `https://sandbox.momodeveloper.mtn.com`,
});
const response = await api.post(
'/collection/v1_0/requesttopay',
{
"amount": "5.0",
"currency": "EUR",
"externalId": "6547864",
"payer": { "partyIdType": "MSISDN", "partyId": "0977948551" }
},
{
headers: {
'Authorization': 'Bearer ' + token,
'X-Reference-Id': 'f9b8b0a-XXXXXXXXXX',
'X-Target-Environment': 'sandbox',
'Ocp-Apim-Subscription-Key': '14d2a71dXXXXXXXXX',
}
}
);
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 working with a JSON rest API that has the following response:
// response
[
{
id: 1,
userId: 1,
start: "2018-01-01 10:15",
finish: "2018-01-01 12:20",
breakLength: 30
},
{
id: 2,
userId: 1,
start: "2018-01-02 10:15",
finish: "2018-01-02 18:20",
breakLength: 45
}
];
See below for code. Like my other functions, I am requesting a GET using fetch(). However, sometimes this function when called requests and responds with a 200, and sometimes it responds with a 400 bad request(Uncaught (in promise) SyntaxError: Unexpected token B in JSON at position 0) It seems very random when it happens. My server which the JSON Rest API is on is localhost:3000 and my application is on localhost:3001. I have used this same method for other JSON requests and they work perfectly. I am not sure why this one is having trouble? Thanks for your help!
Update: It seems as though the last Promise.all, setState is not being executed. The program is crashing on line .then(response => response.json()) in promise3.
Updated Code:
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
callbackSessionId = (sessionId) => {
let promise1 = this.fetchUserAttributes(sessionId)
.then(response => response.json())
.then(json => this.setState({
userAttributes: json
}));
Promise.all([promise1]).then(() => {
let promise2 = this.getOrganisations(sessionId)
.then(response => response.json())
.then(json => this.setState({
organisations: json
}));
let promise3 = this.getShifts(sessionId)
.then(response => response.json())
.then(json => this.setState({
shifts: json
}));
// this.setState({
// sessionId: sessionId
// });
Promise.all([promise2, promise3]).then(() => {
this.setState({
sessionId: sessionId
});
});
});
};
Your JSON is actually invalid. All keys need to be string literals, so your correct JSON would look like this:
[
{
"id": 1,
"userId": 1,
"start": "2018-01-01 10:15",
"finish": "2018-01-01 12:20",
"breakLength": 30
},
{
"id": 2,
"userId": 1,
"start": "2018-01-02 10:15",
"finish": "2018-01-02 18:20",
"breakLength": 45
}
]
There are a few issues in your code: you should always return your promises, headers property names should be quoted and React setState is an asynchronous method.
Please, try to update it like below to see if it works, I'll edit expanding on the details if it does.
getShifts = (sessionId) => {
return fetch("http://localhost:3000/shifts", {
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": sessionId
}
});
};
fetchData = (sessionId) => {
let promise3 = this.getShifts(this.state.sessionId)
.then(response => response.json())
.then(json => this.setState({shifts: json}, this.forceUpdate));
};
I'm building a webapplication in NodeJS.
Back-end in application is connected with user just via Json API. I'm trying to do login option. It's possible? How can I receive response from Passport Authenticate?
function post_api(req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' });
// Check method
if(!req.body.method)
res.write( JSON.stringify({
"status":"400",
"response": {
"status" : "error",
"info": "Method not defined."
}
}));
else
{
if(req.body.method == "login")
{
passport.authenticate('local', {failureFlash: true, successFlash: true});
// Something here but i have no idea what...
res.write( JSON.stringify({
"status":"200",
"response": {
"status" : "error", // or success
"info": req.flash('error')
}
}));
}
else
res.write( JSON.stringify({
"status":"404",
"response": {
"status" : "error",
"info": "Method not found."
}
}));
}
res.end(); };
This of course doesn't works, how it should look like?