Im trying out a weather app with VueJS using the weathermap API. I already got my API key and I still doesn't work on my application. But when I try to use the link for the API in the browser, it shows data in it. But why it doesn't show data in my app. I checked the browser console it display an error Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Here is my code:
export default {
name: 'App',
data(){
return{
api_key: 'f9874496f4c1c5729fc7b4f546b1ebe4',
url_base: "api.openweathermap.org/data/2.5/",
query: '',
weather: {}
}
},
methods: {
fetchWeather(e) {
if(e.key == "Enter") {
fetch(`${this.url_base}weather?q=${this.query}&units=metric&appid=${this.api_key}`)
.then(res=> {
return res.json();
}).then(this.setResults);
}
},
setResults (results) {
this.weather = results;
}
}
}
And here is a photo of the API link I used in the browser.
check it here
I hope someone could help me out with this. Thanks in advance!
you need to catch your errors and print it to find out exactly what is wrong.
fetch(`${this.url_base}weather?q=${this.query}&units=metric&appid=${this.api_key}`)
.then(res=> {
return res.json();
})
.then(this.setResults)
.catch(error=>console.log(error))
this should get rid of the uncaught(promise) error and print the actual error
This must be from "Tyler Potts" Vue weather app tutorial on YouTube. I was stuck here too.
Your url_base needs to include http:// at the beginning:
url_base: 'http://api.openweathermap.org/data/2.5/',
Edit
I believe this is because while we may be used to our browsers including the "http://" protocol at the beginning, so that all we need to do as users is type in the hostname and domain to access a website or data we wish to retrieve, our code will not automatically do the same. So you must specify exactly and fully what the function must fetch.
Related
I'm currently developing a website on my localhost. A key component of the website must make requests to a third-party API (specifically https://api.commonstandardsproject.com/). The request is made via javascript running on the user's browser. However, when I attempt to run the following:
var reqUrl = 'https://api.commonstandardsproject.com/api/v1/jurisdictions';
axios.get(reqUrl, {
headers: {
'Api-Key': "vZKoJwFB1PTJnozKBSANADc3"
}
}).then((response) => {
var parsedResp = JSON.decode(response.data)
this.jurisdictions = parsedResp
}).catch((errors) => {
console.log(errors)
});
I receive a 401 from the API and an error stating that: error: "Unauthorized: Origin isn't an allowed origin.". Interestingly, I can access the API content fine (and without an API key) using just a browser or curl. When I check the origin of my request in the networks tab on chrome, it gives 127.0.0.1:8000. I believe this is the locus of the error, though I am uncertain of how to resolve it.
Can anyone tell me how to fix this? Thanks.
I've slightly modified your code to print the result to the browser console.
var reqUrl = "https://api.commonstandardsproject.com/api/v1/jurisdictions";
axios
.get(reqUrl, {
headers: {
"Api-Key": `MY API KEY`,
},
})
.then((response) => {
console.log(response);
})
.catch((errors) => {
console.log(errors);
});
I created an account and found I got the same results as you.
To get a successful response from the api I had to update my 'ALLOWED ORIGINS' in the sidebar of the https://commonstandardsproject.com/developers page to match the first part of the URL from the index.html file I was running in the browser.
E.g. the URL for the index.html I am running locally is:
http://10.0.1.159/index.html
I updated the ALLOWED ORIGINS to include the string
http://10.0.1.159
Allow Origins example
You will have to add the local address for the page you are testing from in the ALLOWED ORIGINS section of the developer page for the commonstandardsproject where you are signed into your account. Make sure to hit the 'update origins' button after you have entered the correct URL.
I'm trying to verify if the user was able to complete the registration successfully. For this, I want to get the user's token via cookies, as in the following code:
[...]
export async function getServerSideProps(ctx) {
try {
const cookies = nookies.get(ctx)
console.log(JSON.stringify(cookies, null, 2));
const token = await firebaseAdmin.auth().verifyIdToken(cookies.token)
const { email } = token
return {
props: { message: `${email} was successfully registered!`}
}
} catch (err) {
console.log(err)
return { props: { message: 'Error'} }
}
}
[...]
This function returns the following error:
errorInfo: {
code: 'auth/argument-error',
message: 'Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See
https://firebase.google.com/docs/auth/admin/verify-id-tokens for
details on how to retrieve an ID token.' }
I believe I must be misusing nookies.get(ctx), and I say this because the retrieved cookie (token) is equal to a "", which doesn't make much sense to me. Then, how can I properly use nookies to get that token?
I would appreciate it, if anyone could help me to find out what I'm missing out.
Thanks in advance.
EDIT: The user account is created, and the email and password are stored in the Firebase Auth. It is only this piece of code that does not work.
Since Next 10.0.4 you can get cookies without nookies
const cookies = ctx.req.cookies
try in this way, if you still getting token as empty check the way that you set cookies.
I am attempting to integrate the YouTube API into a new Vuejs application and I am testing it in the browser and continuing to get a 404 error.
I did have a www missing, but I continue to get this same error when I make the request. Is there something I am not seeing in my code that is wrong? Is it a cors issue? If so, what is the standard practice for resolving this in Vuejs? I have made a similar application in Reactjs and did not run into this issue.
<template>
<div>
<SearchBar #termChange="onTermChange"></SearchBar>
</div>
</template>
<script>
import axios from "axios";
import SearchBar from "./components/SearchBar";
const API_KEY = "<api_key>";
export default {
name: "App",
components: {
SearchBar
},
methods: {
onTermChange(searchTerm) {
axios
.get("https://www.googleapis.com/youtube/v3/search", {
params: {
keys: API_KEY,
type: "video",
part: "snippet",
q: searchTerm
}
})
.then(response => console.log(response));
}
}
};
</script>
I did notice in the response I got this message:
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
I am not sure what this means.
Put your Api key in url like
"https://www.googleapis.com/youtube/v3/search?key=YOUR_API_KEY"
axios.get("https://www.googleapis.com/youtube/v3/search?key=Your_Api_Key", {
params: {
type: "video",
part: "snippet",
q: searchTerm
}
})
.then(response => console.log(response));
You will find an example as well here
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}
This means that you have exceeded your limit to serve videos from youtube.
You need to create an account to be able to show more videos.
If you're sure you haven't exceeded your limit/ have an account double check your developer console that the API is turned on.
Developer Console.
What I would suggest is to add a catch to your call to handle errors in the future.
axios
.get("https://www.googleapis.com/youtube/v3/search", {
params: {
keys: API_KEY,
type: "video",
part: "snippet",
q: searchTerm
}
})
.then(response => console.log(response));
.catch(err => { console.log(err); }
Solved this by configure/updating/enabling the settings.
The api key worked in the past for me. When returning to use it again, i received a 403 error.
The server understood my request, but denied me access to the info.
Just go into developers console, go to enable apis, search youtube, and enable it, your key will now work as expected.
for some users, this error might be because of cause sanctions. so try to run your project using a DNS or VPN.
I added aftership in my react app the following way:
const Aftership = require('aftership')('put-my-API-KEY', {
endpoint: 'https://api.aftership.com/v4'
});
let query = {
page:10,
limit:5
};
Aftership.call('GET', '/trackings', {
query: query
}, (err, result) => {
console.log(err);
console.log(result);
});
export default Aftership;
When I am using node src/aftership.js in terminal, then fetching data works well (after comment out last line export default Aftership).
But when I fetch from src/containers/Tracking.js file the following way:
import Aftership from '../../aftership';
...
componentDidMount (){
let query = {
page:10,
limit:5
};
Aftership.call('GET', '/trackings', {
query: query
}, (err, result) => {
console.log(err);
console.log(result);
});
}
it's showing me an error in console:
Failed to load https://api.aftership.com/v4/trackings?page=10&limit=5:
Request header field x-aftership-agent is not allowed by
Access-Control-Allow-Headers in preflight response. Tracking.js:28
TypeError: Failed to fetch Tracking.js:28 Undefined
Can anyone help me what is my issue and what should I do know?
This looks like a Cross-Origin Resource Sharing (CORS) problem. To simply put this is happening you are using your local development host with third party instead. To avoid such errors, you can use Chrome extensions like https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi. This extension will edit response header to Access-Control-Allow-Headers: '*', which allows all headers on request body.
This is not recommended for daily use, so I recommend to add wildcard for only APIs you would like to use. In this case add https://api.aftership.com/* to extension settings
My app allows users to specify a server name which is where their installation of our api is. This is so the rest of the app can make calls to that endpoint.
However, I need to display an error message to if we get an error like ERR_NAME_NOT_RESOLVED and it seems that I'm not able to catch this as an error in javascript.
Is there any way around this?
What're you using to make the call to the endpoint? if you're using fetch you don't have an exception, the response is an object with a property error in true and the error messages.
response = {
error: true,
data: { message: 'ERR_NAME_NOT_RESOLVED', code: 404 }
}
If you're using axios, you have to make something like this:
axios.post('/formulas/create', {
name: "",
parts: ""
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});