I'm doing a GET request to a firebase database and when i console log the data the GET request brings it logs "uncaught exception: Object".
.
I've already did the POST http request and didn't have any problem, didn't tried any solution as i cant think of one, it doesn't even give me the line of the error.
<script>
export default {
data:() => ({
blogs:[]
}),
methods:{
},
created(){
this.$http.get('https://recetapp-b43f2.firebaseio.com/posts.json').then(function(data){
console.log(data);
})
}
}
</script>
I expect the data showing the actual JSON files instead of the error.
Try
created() {
this.$http.get("https://recetapp-b43f2.firebaseio.com/posts.json").then(res => {
console.log(JSON.parse(res.data));
});
}
https://recetapp-b43f2.firebaseio.com/posts.json returns 401 (Unauthorized), so you shall rather catch the this.$http (assume Axios) with:
mounted() {
this.$http.get("https://recetapp-b43f2.firebaseio.com/posts.json")
.then(response => { console.log(response.data); })
.catch(e => { console.log(e); })
}
Related
The issue I'm having here is that whenever I deploy my app to either Netlify or Vercel the POST requests specifically being sent to the NextJS APIs are all throwing this error;
ERROR SyntaxError: Unexpected token ' in JSON at position 0
however, when I run the application in either development mode or by building and running locally I'm not having the same issue everything works perfectly.
This is the code I'm using to send the request;
fetch('api/route', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ... data })
})
.then(res => res.json())
.then(data => {
data.error ? reject(new Error(data.error)) : resolve(data)
})
.catch(err => {
console.log(err)
reject(new Error('Network Error'))
})
And, this is an example of the code in the API files;
export default async function handler(req, res) {
const { method } = req
switch (method) {
case 'POST':
const { ... data } = req.body
try {
// Computation
res.status(200).json({ message: 'OK' })
} catch (error) {
console.log(error)
res.status(500)
}
break;
default:
// Invalid Method
console.log(new Error('Invalid Method: ', method))
res.status(405)
}}
I would really appreciate any assistance, I'd really like to know what the problem is.
I found this strange problem where documented feature seems not to be working.
I have this working code:
exports.getEvents = functions.https.onRequest((req, res) => {
cors(req, res, () => {
admin.database().ref('events').orderByValue().once('value', function(snapshot) {
res.status(200).send(snapshot.val());
}).catch(error => {
console.error('Error while reading data', error);
res.status(403).send('Error: ' + error);
});
When I change from once() to on() I get errors.
What I want to achieve is to have server send new JSON payload when there are changes to eventssince I have app that reads events.json directly and I can use only link to provide data (so all SDK functions are out). Am I doing something wrong?
Error log:
TypeError: admin.database(...).ref(...).orderByValue(...).on(...).catch is not a function
at cors (/user_code/index.js:24:11)
at cors (/user_code/node_modules/cors/lib/index.js:188:7)
at /user_code/node_modules/cors/lib/index.js:224:17
at originCallback (/user_code/node_modules/cors/lib/index.js:214:15)
at /user_code/node_modules/cors/lib/index.js:219:13
at optionsCallback (/user_code/node_modules/cors/lib/index.js:199:9)
at corsMiddleware (/user_code/node_modules/cors/lib/index.js:204:7)
at exports.getEvents.functions.https.onRequest (/user_code/index.js:19:2)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:26:47)
at /var/tmp/worker/worker.js:635:7
You've tried to add a .catch to the end of your statement. .on doesn't support this function.
See some sample code below which should fix your issue.
admin.database().ref('/somePath')
.orderByValue()
.on('child_added', (snapshot, prevChildKey) => {
console.log(snapshot.val()); // JSON
}, err => {
// Error is thrown here - Not in a .catch
});
In my Ionic2 app, I have a service which handles all http requests.
I have an alert controller when any error occurs in http call. On button click in this alert I want to run that call again. I am able to do it right now. The problem is response is not resolved to page from which function was called.
Code in service:
loadCity(){
return new Promise(resolve => {
this.http.get(url).map(res=>res.json())
.subscribe(data => {resolve(data)},
err => { this.showAlert(err); }
});
}
showAlert(err: any){
// code for alert controller, I am only writing handler of alert
//controller refresh button
handler => {this.loadCity();}
}
Code in CityPage
showCity(){
this.cityService.loadCity()
.then(data => {//process data});
}
Handler is calling function again but this time promise is not resolved to CityPage showCity() function.
When an error occurs in the http request, the error callback function is being called, but you are neither resolving nor rejecting the promise.
You can do something like
loadCity(){
return new Promise( (resolve, reject) => {
this.http.get(url).map(res=>res.json())
.subscribe(
data => {resolve(data)},
err => {
this.showAlert(err);
reject(err);
}
});
}
}
and in the caller
showCity(){
this.cityService.loadCity()
.then( data => {
//process data
})
.catch( error => {
//some error here
})
}
You can see better examples in the docs.
I am having this problem where I make HTTP Request to the API and in case of error ( specially error 500) the JS just breaks or goes into infinite loop and I should close the window and re-open the page. What I need is a message to pop up and in very generic way explain what happened. How should I handle this kind of error any ideas?
Example Request:
this.$http.get('people', { params }).then(({ data }) => {
this.setFetching({
fetching: false
})
})
then accepts a second callback to handle errors. You can also supply a .catch in addition to a .then to handle more severe failures.
new Vue({
el: '#app',
data: {
fetching: true
},
mounted() {
this.$http.get('people')
.then(() => {
this.setFetching({
fetching: false
})
},
(err) => {
console.log("Err", err);
})
.catch((e) => {
console.log("Caught", e);
})
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.2.1/vue-resource.min.js"></script>
<div id="app">
</div>
I'm very bad when it comes to thinking of a title question, sorry for that.
My Problem:
I'm unit testing my async redux actions like it's suggested in the docs. I mock the API calls with nock and check for the dispatched actions with redux-mock-store. It works great so far, but I have one test that fails even though it clearly does work. The dispatched action neither does show up in the array returned by store.getActions() nor is the state changed in store.getState(). I'm sure that it does happen because I can see it when I test manually and observe it with Redux Dev Tools.
The only thing that is different in this action dispatch is that it is called in a promise in a catch of another promise. (I know that sounds confusing, just look at the code!)
What my code looks like:
The action:
export const login = (email, password) => {
return dispatch => {
dispatch(requestSession());
return httpPost(sessionUrl, {
session: {
email,
password
}
})
.then(data => {
dispatch(setUser(data.user));
dispatch(push('/admin'));
})
.catch(error => {
error.response.json()
.then(data => {
dispatch(setError(data.error))
})
});
};
}
This httpPost method is just a wrapper around fetch that throws if the status code is not in the 200-299 range and already parses the json to an object if it doesn't fail. I can add it here if it seems relevant, but I don't want to make this longer then it already is.
The action that doesn't show up is dispatch(setError(data.error)).
The test:
it('should create a SET_SESSION_ERROR action', () => {
nock(/example\.com/)
.post(sessionPath, {
session: {
email: fakeUser.email,
password: ''
}
})
.reply(422, {
error: "Invalid email or password"
})
const store = mockStore({
session: {
isFetching: false,
user: null,
error: null
}
});
return store.dispatch(actions.login(
fakeUser.email,
""))
.then(() => {
expect(store.getActions()).toInclude({
type: 'SET_SESSION_ERROR',
error: 'Invalid email or password'
})
})
});
Thanks for even reading.
Edit:
The setErroraction:
const setError = (error) => ({
type: 'SET_SESSION_ERROR',
error,
});
The httpPostmethod:
export const httpPost = (url, data) => (
fetch(url, {
method: 'POST',
headers: createHeaders(),
body: JSON.stringify(data),
})
.then(checkStatus)
.then(response => response.json())
);
const checkStatus = (response) => {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
};
Because of you are using nested async function in catch method - you need to return the promise:
.catch(error => {
return error.response.json()
.then(data => {
dispatch(setError(data.error))
})
});
Otherwise, dispatch will be called after your assertion.
See primitive examples:
https://jsfiddle.net/d5fynntw/ - Without returning
https://jsfiddle.net/9b1z73xs/ - With returning