retrieve JSON response from Frisby POST in another function - javascript

i got a frisby function
createPOST = function () {
return frisby.post(url, {
body: qs.stringify({
username: data.user,
password: data.password
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then((resp) => {
let respJson = resp.json;
return respJson;
}, (error) => {
console.error("Error:: " + error);
throw error;
});
}
and second function
getRespJson = function () {
createToken().then(function (value) {
console.log("resp::"+value);
});
}
im trying to retrieve this json response in another function, but not able to using frisby. no log is even displaying

If your data coming in the body(that you are expecting) or anywhere, simply store into other variable and then by nested way you able to use it. if you have multiple nested body then in that situation you also able to use it.
I'm using the same with that workaround.
or try to use it by storing that into another file.
Thanks

Related

issue accessing retrieved data from API which was pushed into a useState array - react ts

I am attempting to render data which was retrieved from my backend server.
The connection works fine and i'm able to retrieve a response.. My problem is that once I have loaded the information into my state-array, I cannot seem to access the properties within.
My useState array filled with the API request's data:
my backend's method i'm calling from my react program:
router.route("/api/issues").get(getAllIssues);
the route is calling the following function:
export const getAllIssues = async (
req: Request,
res: Response
): Promise<void> => {
try {
const issues: IssueInterface[] = await Issue.find({});
res.status(200).json({ issues });
} catch (err) {
throw err;
}
};
fetching the data from the api:
function Issues({ }: Props) {
const [issuesList, setIssuesList] = useState<IssueInterface[]>([]); // we retrieve from DB issues - we need it to look the same object's structure
useEffect(() => {
try {
axios({
method: 'get',
url: 'http://localhost:8001/api/issues',
headers: { 'Content-type': "application/json" }
}).then((response) => {
console.log(typeof (response))
const issuesStringified = JSON.stringify(response.data)
console.log("stringified: " + issuesStringified)
console.log(issuesList)
})
} catch (err) {
console.log("error : " + err);
}
}, [])
now my attempt to render parts of the array by using the following return function:
return (
<Stack>
<div>
{hasLoaded ? issuesList.map((issue: IssueInterface) => <div><h1>company: {issue.company_name}</h1></div>) : <></>}
</div>
</Stack>
)
provides the following outcome:
as if, it is unable to access the properties of each element.
any idea what am I doing wrong here?
regards! :_)

How can I delete some data from Firebase Realtime Database?

I have this functions to save and get data on it:
to save:
try {
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', {
method: 'post',
body: JSON.stringify(addNewLocation)
})
const response = await fetch(request)
window.location.reload()
return await response.json()
} catch (error) {
alert('Try again: ', error)
}
//to get:
try {
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'get'})
const response = await fetch(request)
return await response.json()
} catch (error) {
alert('Try again: ', error)
}
And when I use "delete" instead of "get" it deletes the locations folder entirely, but when I use a link with a key at the end of the link, I get an error
You need make a DELETE request at the location you need to delete.
curl -X DELETE \
'https://[PROJECT_ID].firebaseio.com/locations.json'
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations.json', { method: 'DELETE'})
const response = await fetch(request)
return await response.json()
I'm not sure about how your database structure looks like but the above request will delete the whole "locations" node. Here's an example:
If you want to delete only location2, then make a delete request at https://[PROJECT_ID].firebaseio.com/locations/location2.json
I'm not sure if there's any specific reason for you to use the REST API but you can try using Firebase Web SDK. It's easier to use, for example to delete location2:
firebase.database().ref("locations/location2").remove()
you can use the remove method
let userRef = this.database.ref('users/' + userId);
userRef.remove()
You can use the following code
deleteSomeData(id) {
fetch(
// don't add .json at [data Name]
`https://[your FireBase project url]/[data Name (don't add .json)]/${id}.json`,
{
method: 'Delete',
headers: {
'Content-Type': 'application/json',
},
}
)
.then((response) => {
if (response.ok) {
// if sucess do something
} else {
// if fail throw error
throw new Error('could not delete data');
}
})
.catch((error) => {
this.error = error.message;
console.log(id);
});
},
You can user item id to delete it like below.
const request = new Request('https://yandexmap-96969-default-rtdb.firebaseio.com/locations/<localtion_id>.json', { method: 'delete'})
your location id can be value like this, -MyB0qQoQuf9lPnwderfg

Extracting token from the URL and sending a post request using Axios - Vue js

I have been trying to extract a token from say http://test.com/confirm?token=MMsndiwhjidh... and then send a post request to another server.
I have tried this:
export default {
data() {
return {
confirmation : false,
somethingWrong: false
}
},
created: function() {
axios.post('/confirm', null, {
method: 'post',
params: {
token:this.$route.query.token
}
})
.then(function(res) {
console.log(res)
this.confirmation = true
})
.catch(function(error) {
console.log(error)
this.somethingWrong = true
})
}
}
I got the following errors:
I think I am not able to extract the token properly.
The reason is you're using declarative functions instead of arrow functions in your then / catch blocks. The this don't refer to the same thing (here, this is not your Vue component).
Try like this:
.then((res) => {
console.log(res)
this.confirmation = true
})
I won't try to explain the difference myself as there are plenty of articles on the web about it. Here's one

TypeError: data.filter is not a function

I am trying to filter an array of JSON objects, which I get from an API call on my proxy. I am using a Node.js web framework Express to make the API call.
API returns the following:
{
data: [
{
type: "aaa",
name: "Cycle",
id: "c949up9c",
category: ["A","B"]
},
{
type: "bbb",
name: "mobile",
id: "c2rt4Jtu",
category: ["C","D"]
},
...
]
}
server.js
function sortDataByID(data) {
return data.filter(function(item) {
return item.id == 'c949up9c';
});
}
app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
headers: {
'Authorization': 'hgjhgjh',
'Accept': 'application/json'
}
}
request.get(options).pipe(sortDataByID(res));
});
I keep getting the following error message.
TypeError: data.filter is not a function
What is the obvious mistake here? Anyone?
I think your mistake is to think than res is the data than you expect.
But if you take a look inside res you should find the data.
so you must get datafrom the res and use it.
For example:
const data = res.data;
request.get(options).pipe(sortDataByID(data))
Have a nice day !
I've personally never seen piping to a function. I don't think that should work. In any case:
You can use a callback instead of piping. Try this:
app.get('/products', (req, res) => {
const options = {
url: BASE_URL + '/products',
json: true, //little convenience flag to set the requisite JSON headers
headers: {
'Authorization': 'hgjhgjh',
'Accept': 'application/json'
}
}
request.get(options, sortDataByID);
});
function sortDataByID(err, response, data){ //the callback must take 3 parameters
if(err){
return res.json(err); //make sure there was no error
}
if(response.statusCode < 200 || response.statusCode > 299) { //Check for a non-error status code
return res.status(400).json(err)
}
let dataToReturn = data.data.filter(function(item) { //data.data because you need to access the data property on the response body.
return item.id == 'c949up9c';
}
res.json(dataToReturn);
}
I received TypeError: data.filter is not a function while doing Unit testing.
I was passing an object not an array in the result.
gateIn$: of({}),
instead of
gateIn$: of([]),
gateIn$.pipe(takeUntil(this.destroy$)).subscribe(bookings => (this.dataSource.data = bookings));
once you see the error it is pretty obvious, the hard bit is spotting it in the first place.

React-native async fetch returns null

I am trying to put fetch functions into a separated file, so I can organise these API fetch easily. However, when I try to fetch and return the data, it gives me null or an unexpected json object. Here is part of my src:
//api.js
export async function LoginAPI(username, password) {
const url = baseURL + "/login/";
var params = {username: username, password: md5.hex_md5(password)};
let response = await fetch(url, {
method: 'POST',
headers: {'Accept': 'application/json','Content-Type': 'application/x-www-form-urlencoded'},
body: JSON.stringify(params)
});
return await fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(params)
})
.then((res) => res.text())
.then((text) => text.length ? JSON.parse(text) : {})
.catch((error) => {
throw error;
});
};
Here is the another file.
//index.js
var Login = React.createClass({
onPress_login: function() {
var value = this.refs.form.getValue();
if (value) {
result = LoginAPI(value.username, value.password);
console.log(result);
} else {
this.AlertDialog.openDialog();
}
},
render() {
return (
(...)
<Button onPress={this.onPress_login}>
<Text>Login</Text>
</Button>
The fetch is working, it is communicating with the server. However, the console log returns me this at the first place
Promise _45: 0_54: null _65: null _81: 1 __proto__: Object
I am assuming that the result log in the console at the first place is not the await result (the actual response from server, but an object of fetch response). I tried to search out methods online but I can't find any post/blog/article saying how to do fetch as a function call.
Is there any way to do like swift, LoginAPI(username, password, callback: {...}) please?
The problem is that you're are making an async function and not waiting for the response, the you see that kind of console log.
Try this:
result = await LoginAPI(value.username, value.password);
Let me know if this was your problem.

Categories

Resources