I'm writing code for a weather journal app. The thing is when I pass to fetch method the URL of the site of openweathermap.com with the zip code and country code way it only accepts the country code as the US it never accepts another country. I tried so many but it never accepts any of those it only returns the data object of forecast to the US and for any other country it just shows the message city not found. Here is my code:
const generate = document.getElementById('generate').addEventListener('click', function(){
const zip = document.getElementById('zip').value;
const countryCode = document.getElementById('countryCode').value;
endPointData(zip,countryCode,apiKey);
})
const endPointData = async (zip,countryCode,apiKey) => {
const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},${countryCode}&appid=${apiKey}`);
try{
const data = await res.json();
console.log(data);
}
catch(error){
// appropriately handles the errors.
console.log("error",error);
}
}
const postData = async (url='', data = {}) => {
const response = await fetch(url,{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
});
try{
const newData = await response.json();
return newData;
}catch(error){
console.log("error",error);
}
}
Working fine for me in other countries as well.
const apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const zipCode = "110007";
const countryCode = "IN";
const endPointData = async (zipCode, countryCode, apiKey) => {
const URL = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},${countryCode}&appid=${apiKey}`;
const res = await fetch(URL);
try {
const data = await res.json();
console.log(data);
}
catch(error){
// appropriately handles the errors.
console.log("error",error);
}
}
endPointData(zipCode, countryCode, apiKey);
console.log your URL variable. Maybe your country code is empty.
The API falls back to US as default when country code is not specified.
https://openweathermap.org/current#zip
Try it at postman first (https://www.postman.com/)!
Related
am trying to save a data from fetch api to my database using mongoose so
the data never come.
could anyone help? and thank you,
this is my code
`
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/Quran')
const SurahSchema = mongoose.Schema({
ayahs:[{
number:Number,
numberInSurah:Number,
text:String
}],
englishName:String,
englishNameTranslation:String,
name:String,
number:Number,
revelationType:String,
});
var surah = mongoose.model('Surah',SurahSchema)
`
`
const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani'
async function getdata(){
const res = await fetch(API)
const data = await res.json()
for (let i = 0; i < data.data.surahs.length; i++) {
const Surah = new surah({
ayahs:[{
number:data.data.surahs[i]['ayahs'].number,
numberInSurah:data.data.surahs[i]['ayahs'].numberInSurah,
text:data.data.surahs[i]['ayahs'].text
}],
englishName:data.data.surahs[i]['englishName'],
englishNameTranslation:data.data.surahs[i]['englishNameTranslation'],
name:data.data.surahs[i]['name'],
number:data.data.surahs[i]['number'],
revelationType:data.data.surahs[i]['revelationType']
})
Surah.save(function (err) {
if (err) return handleError(err);
// saved!
});
}
}
getdata()
`
i tried to search about the problem in google and i did not find anything similar.
Instead of writing such a complicated for loop, you can just use the .insertMany() method on the model
const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani'
async function getdata(){
const res = await fetch(API);
const data = await res.json();
try{
const inserted = await surah.insertMany(data.data.surahs);
}catch(e){
console.log("Some error");
console.log(e);
}
}
getdata()
the following is a complete working snippet
import mongoose from 'mongoose';
import fetch from 'node-fetch';
mongoose.connect('mongodb://localhost:27017/Quran');
const SurahSchema = mongoose.Schema({
ayahs: [
{
number: Number,
numberInSurah: Number,
text: String,
},
],
englishName: String,
englishNameTranslation: String,
name: String,
number: Number,
revelationType: String,
});
const surah = mongoose.model('Surah', SurahSchema);
const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani';
async function getdata() {
const res = await fetch(API);
const data = await res.json();
try {
const inserted = await surah.insertMany(data.data.surahs);
console.log(inserted);
process.exit(0);
} catch (e) {
console.log('Some error');
console.log(e);
process.exit(0);
}
}
getdata();
this inserted 114 documents
PS: you just need to install node-fetch and mongoose
Inside my userDB.json file it looks like this;
[{
"username": "john",
"xp": 5
},
{
"username": "jane",
"xp": 0
}
]
Inside the app.js file ;
async function getUsers() {
let url = 'userDB.json';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
async function addUser(username){
let users = await getUsers();
let newUser = {"username": `${username}`,"xp": 0};
users.push(newUser);
}
addUser('testName');
async function renderUsers() {
let users = await getUsers();
let html = '';
users.forEach(user => {
let htmlSegment = `<div class="user">
<h2>${user.username} ${user.xp}</h2>
</div>`;
html += htmlSegment;
});
let container = document.querySelector('.container');
container.innerHTML = html;
}
renderUsers();
I would like to send a data to my local database and save it then I would like to render database array items on screen. But when I console.log the users in addUser() function added item visible on console but not rendered or saved on local file how to do that?
What you are doing in addUser() is to get the array from your database, mutating it by pushing a new item in it, but that only affects that specific array you got, not the database.
For this to work you need to make a post request to a backend that would update your database and then call renderUsers() to get the updated data:
async function addUser(username) {
let url = "/"; // ⚠️ whatever url that accept a post request
let newUser = { username: username, xp: 0 };
await fetch(url, { method: "POST", body: JSON.stringify(newUser) });
renderUsers();
}
I have a react App which I will be using to bring in google other contacts and I see that theres a limit for 1000 contacts in each call to google People Api's.
const getGoogleContacts = async (token) => {
if(!token) throw new Error('Google Auth Token Missing');
let params = {"readMask" : "emailAddresses,names", "pageSize" : "1000"};
let url = `https://people.googleapis.com/v1/otherContacts?${new URLSearchParams(params)}`;
let headers = { Authorization: `Bearer ${token}`};
let rawData = await fetch(url, { headers })
.then(res => res.text());
let parsedJson = JSON.parse(rawData);
let nextPageCheck = checkForNextPageToken(parsedJson);
if(nextPageCheck){
//get the next page contacts.
}
return handleRawContactData(parsedJson);
}
const checkForNextPageToken = (response) => {
if(response.hasOwnProperty('nextPageToken')){
return true;
}
return false;
}
I am using jsonbin.io and hosted a json data as private bin.
I am calling a axios get request to fetch that data. I have to pass my secret-key in headers as
headers{
secret-key: mysecretkey
}
but axios does not allow key in header as secret-key
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
secret-key: secretKey,
},
});
console.log(response); };
secret-key gives error at compile time and "secret-key" can not fetch data what should i do now ?
secret-key is not a valid identifier in JavaScript, as they cannot contain hyphens (see the specification for more details.
In your case, you can simply put the name of your header in quotes, like this:
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
"secret-key": secretKey,
},
});
console.log(response);
};
it should be
const fetchPhotosFlocal = async () => axios.get(localUrl, {
headers: {
'secret-key': secretKey,
},
});
const resp = await fetchPhotosFlocal();
console.log(resp);
Problem solved i checked their documentation they are passing secret_key in string code.
req.setRequestHeader("secret-key", "<SECRET_KEY>");
This runs fine
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
"secret-key": secretKey,
},
});
console.log(response); };
HHi,
I'm working on a project for an online course and I need to make one change to the project. I don't exactly understand what the code reviewer is saying I'm doing wrong. His comment is:
Here you need to fire a new GET request to fetch the data from server.
The requests GET and POST have a specific purpose.
GET request to fetch data from server/db
POST is used to create new data in server/db
These requests must do the task they are designed for, nothing else.
This is the problem area of my code:
let postData = async(url = '', data = {})=>{
console.log(data);
let temp = data.main.temp;
let zip = document.getElementById('zip').value;
let feelings = document.getElementById('feelings').value;
let date = newDate;
let response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify( { temp, zip, feelings, date }),
});
try {
const newData = await response.json();
console.log(newData);
document.getElementById("date").innerHTML = newData.date;
document.getElementById("temp").innerHTML = newData.temp;
document.getElementById("content").innerHTML = newData.feelings;
return newData
}catch(error) {
console.log("error", error);
}
}
This is my full code:
app.js:
let apiURL = 'http://api.openweathermap.org/data/2.5/weather?id=524901&APPID=' + apiKey + '&zip=';
const endURL = ',us';
// Create a new date instance dynamically with JS
let d = new Date();
let newDate = d.getMonth()+'.'+ d.getDate()+'.'+ d.getFullYear();
document.getElementById('generate').addEventListener('click', performAction);
let content = document.getElementById('feelings').value;
function performAction(e){
let zip = document.getElementById('zip').value;
let url = apiURL + zip + endURL;
apiCall(url)
.then(async function(data){
console.log(data);
let res = await postData('/', data);
console.log(res);
});
};
const apiCall = async (url) =>{
const res = await fetch(url);
try {
const data = await res.json();
console.log(data)
return data;
} catch(error) {
console.log(error)
}
};
let postData = async(url = '', data = {})=>{
console.log(data);
let temp = data.main.temp;
let zip = document.getElementById('zip').value;
let feelings = document.getElementById('feelings').value;
let date = newDate;
let response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify( { temp, zip, feelings, date }),
});
try {
const newData = await response.json();
console.log(newData);
document.getElementById("date").innerHTML = newData.date;
document.getElementById("temp").innerHTML = newData.temp;
document.getElementById("content").innerHTML = newData.feelings;
return newData
}catch(error) {
console.log("error", error);
}
}
server.js:
let projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser');
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const cors = require('cors');
app.use(cors());
// Cors for cross origin allowance
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
const port = 8000;
const server = app.listen(port, listening);
function listening(){
console.log(`running on localhost: ${port}`);
};
app.get('/weather', getData);
function getData(req, res){
res.send(projectData)
console.log(projectData)
};
app.route('/')
.get(function (req, res) {
res.sendFile('index.html', {root: 'website'})
})
.post(getWeather);
function getWeather(req, res){
console.log(req.body);
projectData = req.body;
console.log(projectData);
res.status(200).send(projectData);
};
I have no idea what the changes would look like because I wrote this code following the same structure that they taught in the lessons. Any help would be greatly appreciated.
Thanks alot,
Mike
I think you are trying to fetch data from API so he is trying to say that when you are trying to fetch data from api you need GET request.
I figured it out. I needed to write this function:
const updateUI = async () =>{
const res = await fetch('/weather');
try {
const allData = await res.json();
console.log(allData)
document.getElementById("date").innerHTML = allData.date;
document.getElementById("temp").innerHTML = allData.temp;
document.getElementById("content").innerHTML = allData.feelings;
return allData
} catch(error) {
console.log(error)
}
};
and edit my postData function to this:
let postData = async(url = '', data = {})=>{
console.log(data);
let temp = data.main.temp;
let zip = document.getElementById('zip').value;
let feelings = document.getElementById('feelings').value;
let date = newDate;
let response = await fetch(url, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify( { temp, zip, feelings, date }),
});
try {
updateUI()
/* const newData = await response.json();
console.log(newData);
document.getElementById("date").innerHTML = newData.date;
document.getElementById("temp").innerHTML = newData.temp;
document.getElementById("content").innerHTML = newData.feelings;
return newData
*/
}catch(error) {
console.log("error", error);
}
}