trying to obtain data using fetch - fetch

im trying to use fetch to pull and show a balance of a specific user
function handle(){
console.log(email);
fetch('/account/findOne/${email}')
.then(response => response.json())
.then(balance => {
try {
console.log(user.balance);
setBalance('Your balance is: $' + user.balance);
} catch(err) {
console.log('Error');
}
});
}
this is the error i get in my console
:3000/#/balance/:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
can anyone help point me in the right direction?

Related

Unable to use array's method "find" in Vue 3

I am trying to get current location of a user and then push it into array. Before I do so, I check whether a city with the same name is already there. In that case, I won't push it into the array. However, when I am trying to check it, it says: Uncaught (in promise) TypeError: Cannot read properties of null (reading 'find').
const found = ref(false);
const weatherResponse = ref([]);
function getLocation() {
console.log("SETTING LOCATION");
navigator.geolocation.getCurrentPosition((position) => {
console.log(`Lat: ${position.coords.latitude}, Lon: ${position.coords.longitude}`);
if (position.coords.latitude && position.coords.longitude) {
axios.get(`https://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${Math.round(position.coords.latitude)},${Math.round(position.coords.longitude)}&aqi=no`)
.then((response) => {
found.value = weatherResponse.value.find((item) => item.location.name == response.data.location.name);
if (response.data?.error?.code != 1006 && !found.value) {
weatherResponse.value.push(response.data);
this.$store.commit("addToList", response.data);
console.log(weatherResponse.value);
}
})
}
},
(error) => {
console.log(error.message);
}
)
}
I've already tried using fetch, axios to grab the API, but the "find()" method is still not working. Regarding "found" variable, I tried using it in ref as well as declaring it as "let found".
After trying and testing, I've finally managed to get everything to work. My issue was in (weirdly) main.js. Because it was set out like this: createApp(App).use(cors, store).mount('#app') it, I guess, caused VueX.store not to load in properly because mounted hook was called and it was throwing all sorts of mistakes. Putting it like const app = createApp(App); app.use(store); app.use(cors); app.mount("#app"); actually made it work.

Sequelize delete request with payload works with Postman but not with Vue Frontend implementation

I am trying to send PUT and DELETE requests with my express backend to a sqlite database. Put request works fine but DELETE request always fails.
I already checked the headers within the network tab, it seems to be the right one for both (application/json)
With postman, I can easily delete entries, but with my frontend the body does not seem to be set correctly.
const countryToPush = {title: countryName}
try{
await CountryService.post(countryToPush)
console.log(countryName + ' added!')
} catch(err)
{
console.log(err)
}
},
removeFromDb: async function(countryName){
const countryToDelete = {title: countryName}
try{
await CountryService.delete(countryToDelete)
console.log(countryName + ' deleted!')
} catch(err)
{
console.log(err)
}
}
This is within my vue file where I get the 'countryName' from an on click function.
try {
const country = await Country.create(req.body)
res.send(country)
} catch (err) {
res.status(500).send({
error: 'an error has occurred trying to create the country'
})
}
},
async delete (req, res) {
try {
const toDelete = await Country.findOne({
where: {
title: req.body.title
}
})
await toDelete.destroy()
res.send(req.body.title + ' was deleted')
} catch (err) {
res.status(500).send({
error: 'an error has occurred trying to delete the country'
})
}
}
Whereas this is the example from my sqlite calls
Unfortunately, the DELETE request from my vue frontend always fails and gives me the defined error 500 an error has occurred trying to delete the country.
Any ideas what else I could try to get it working?
Model.delete() is not a Sequelize function, you want to use Model.destroy().
await CountryService.destroy(countryToDelete)
Right now you are swallowing the actual error - add console.log(err) to your catch to see that it is probably saying CountryService.destroy is undefined.

fetch api catches exception occurring during react component rendering

I have an action creator like this:
export function createTransaction (customerId) {
return (dispatch) => {
return fetch(`/api/customers/${customerId}/transactions`, {
method: 'post'
})
.then(response => {
dispatch(receiveNewTransaction())
})
.catch(err => {
console.log(err)
alert('Something went wrong while creating transaction', err)
})
}
}
The value dispatched results in re-rendering of the component tree.
Inside render method of one of the components, somewhere deep in the tree, there is a function like this:
transactions.map(item => item)
Strangely, "transactions" above is not an array due to which an exception occurs, which is completely okay. What is not okay (imo) is the excection begin caught by the action creator!! Is it normal??
So, when the api call finishes, i see an error message in the browser console followed by the alert. This is the error message:
TypeError: transactions.map is not a function

How to return base response from Firebase Hosting when accessed via Cloud Function

I'm trying to drop custom json+ld on to my Firebase site. I'm trying to do this by intercepting ("rewriting") the request to my site using Cloud Functions, getting some json+ld information via the Fetch API, then adding that to the content Firebase would normally serve up at the original path.
Is there a way to get the "base" request that Firebase would serve up, and append something to it?
Here's my code:
exports.eventJsonLd = functions.https.onRequest((req, res) => {
if (req.path == '/') {
fetch('http://pathtoMyApi?clientIp=' + req.ip).then(resp => {
if (resp.ok) {
return resp.json();
}
throw new Error('Could not retrieve json+ld');
})
.then(x => {
//*** right here is where I would like to take this script tag
//*** and insert it into the body of the normal request to this path
res.send('<script type="application/ld+json">' + JSON.stringify(x[0]).replace(/typeString/g, '#type').replace(/contextString/g, '#context') + '</script>');
})
.catch(err => {
console.log('Fetch error: ' + err.message);
res.status(500).send(err.message);
});
}
});
Any clues? Thanks.
UPDATE:
What about if I were to do something like
<script type='application/ld+json' src='http://path-to-my-cloud-function/'></script>
? It's not working for me right now . . . but could something like that be a solution?

Meteor 1.3 + React: detect subscription failure?

I have a simple Meteor subscription, and I display a loading message while the data is being loaded. But I don't know how to display error message if subscription failed.
export const MyAwesomeComponent = createContainer(() => {
let sub = Meteor.subscribe('some-data');
if (!sub.ready()) return { message: 'Loading...'};
if (sub.failed()) return { message: 'Failed.' }; // How to do this?
return {
data: Data.find().fetch()
}
}, MyInternalRenderComponent);
Problem is, the subscription object doesn't have a failed() method, only a ready() query. How to pass the failure of a subscription as props in a createContainer() method?
I know the Meteor.subscribe method has an onStop callback for this case, but I don't know how to glue it toghether that to pass a property.
After a lot of researching I managed to get this working and I think it answers your question.
Bear in mind I'm using Meteor 1.6, but it should give you the info to get it working on your side.
On the publication/publish:
try {
// get the data and add it to the publication
...
self.ready();
} catch (exception) {
logger.error(exception);
// send the exception to the client through the publication
this.error(new Meteor.Error('500', 'Error getting data from API', exception));
}
On the UI Component:
const errorFromApi = new ReactiveVar();
export default withTracker(({ match }) => {
const companyId = match.params._id;
let subscription;
if (!errorFromApi.get()) {
subscription = Meteor.subscribe('company.view', companyId, {
onStop: function (e) {
errorFromApi.set(e);
}
});
} else {
subscription = {
ready: () => {
return false;
}
};
}
return {
loading: !subscription.ready(),
company: Companies.findOne(companyId),
error: errorFromApi.get()
};
})(CompanyView);
From here all you need to do is get the error prop and render the component as desired.
This is the structure of the error prop (received on the onStop callback from subscribe):
{
error: String,
reason: String,
details: String
}
[Edit]
The reason there is a conditional around Meteor.subscribe() is to avoid an annoying infinite loop you'd get from the natural withTracker() updates, which would cause new subscriptions / new errors from the publication and so on.

Resources