Closed romebell closed 3 years ago
errors: [ { message: 'API key not valid. Please pass a valid API key.', domain: 'global', reason: 'badRequest' } ] }
### It's something to do with my configurations or files setup is missing something
### I have tried trail and error, youtube videos
I keep getting this error
this is how my weather route is set up
@canourrea23 what API are you trying to access data from?
@fmuwanguzi you spelled response
wrong on line 5
@romebell that didn't change anything I'm not sure if maybe it order in which i put my code in
In creating my table I was able to create it but I keep getting a problem to migrate it.
let searchTerm = res.newLocation;
// searchTerm = res.newLocation;
newLocation = res.Washington;
const newLocation = {
method: 'GET',
url: `https://www.numbeo.com/cost-of-living/in/${newLocation}`
};
request({searchTerm}, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
let title = $('tr').attr('class', 'first_currency');
let milkPrice = Number($('.first_currency').find('span').text().split('\n')[10].split('$')[0]);
console.log(milkPrice);
location.get('/city/:city', (req,res)=> {
console.log(req.params.city);
const city = req.params.Washington
const newLocation = {
method: 'GET',
url: `https://www.numbeo.com/cost-of-living/in/${city}`
};
request({city}, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
and I get SyntaxError: Unexpected end of input
let searchTerm = res.newLocation; // needs to be in a route to get access to res
newLocation = res.Washington;
const newLocation = {
method: 'GET',
url: `https://www.numbeo.com/cost-of-living/in/${newLocation}`
};
request({searchTerm}, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
let title = $('tr').attr('class', 'first_currency');
let milkPrice = Number($('.first_currency').find('span').text().split('\n')[10].split('$')[0]);
console.log(milkPrice);
You can only use res
inside of a route like so:
app.get("/", (req, res) => {
console.log(res);
res.send('Hello, Carolina');
})
Is this a route that you made inside of a location.js
file? Double check to make sure that you have all your parenthesis is the right place.
location.get('/city/:city', (req,res)=> {
console.log(req.params.city);
const city = req.params.Washington
const newLocation = {
method: 'GET',
url: `https://www.numbeo.com/cost-of-living/in/${city}`
};
request({city}, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
comment
model associations, I'm thinking:models.comment.belongsToMany(models.user);
models.comment.belongsToMany(models.game);
user
modelmodels.user.hasMany(models.comment);
models.user.hasMany(models.game);
game
modelmodels.game.hasMany(models.comment);
models.game.belongTo(models.user);
Is this a route that you made inside of a
location.js
file? Double check to make sure that you have all your parenthesis is the right place.location.get('/city/:city', (req,res)=> { console.log(req.params.city); const city = req.params.Washington const newLocation = { method: 'GET', url: `https://www.numbeo.com/cost-of-living/in/${city}` }; request({city}, (err, res, body) => { if (err) return console.error(err); let $ = cheerio.load(body);
Is this a route that you made inside of a
location.js
file? Double check to make sure that you have all your parenthesis is the right place.location.get('/city/:city', (req,res)=> { console.log(req.params.city); const city = req.params.Washington const newLocation = { method: 'GET', url: `https://www.numbeo.com/cost-of-living/in/${city}` }; request({city}, (err, res, body) => { if (err) return console.error(err); let $ = cheerio.load(body);
I have it in my profile.js but that's why I did const city = req.params.Washington
I thought it would plug Washington in
@AlexJBustillos This line is giving back some issues. It looks like you're searching for the user by an ID in req.body.id , but comes back as undefined. You're only passing up the strainId
in the form, but you will also need to pass up the user id
somehow.
const express = require("express");
const app = express();
require('dotenv').config()
const cheerio = require('cheerio');
const request = require('request');
//const layouts = require('express-ejs-layouts');
const session = require('express-session');
const passport = require('./config/ppConfig');
const flash = require('connect-flash');
const db = require("./models");
const SECRET_SESSION = process.env.SECRET_SESSION;
console.log('SECRET_SESSION', SECRET_SESSION);
app.set('view engine', 'ejs');
app.use(require('morgan')('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
//app.use(layouts);
const sessionObject = {
secret: SECRET_SESSION,
resave: false,
saveUninitialized: true
}
app.use(session(sessionObject));
// Initialize passport and run through middleware
app.use(passport.initialize());
app.use(passport.session());
// Flash
// Using flash throughout app to send temp messages to user
app.use(flash());
// Messages that will be accessible to every view
app.use((req, res, next) => {
// Before every route, we will attach a user to res.local
res.locals.alerts = req.flash();
res.locals.currentUser = req.user;
next();
});
app.get('/', (req, res) => {
console.log(res.locals.alerts);
res.render('index', { alerts: res.locals.alerts });
});
let city = Washington;
const city = {
method: 'GET',
url: `https://www.numbeo.com/cost-of-living/in/${city}`
}
request(${newLocation}, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
let title = $('tr').attr('class', 'first_currency');
let milkPrice = Number($('.first_currency').find('span').text().split('\n')[10].split('$')[0]);
console.log(milkPrice);
});
const PORT = process.env.PORT || 3000;
app.get("/thing", (req, res) => res.send("Connected"));
const server = app.listen(PORT, () => {
console.log(`You are connected ${PORT} 🎧`);
});
module.exports = server;
Getting syntax error around my range when SQL parses it. This is the closest I've gotten to making it work because SQL is actually seeing values this time
@canourrea23 What are trying to do here?
const express = require("express"); const app = express(); require('dotenv').config() const cheerio = require('cheerio'); const request = require('request'); //const layouts = require('express-ejs-layouts'); const session = require('express-session'); const passport = require('./config/ppConfig'); const flash = require('connect-flash'); const db = require("./models"); const SECRET_SESSION = process.env.SECRET_SESSION; console.log('SECRET_SESSION', SECRET_SESSION); app.set('view engine', 'ejs'); app.use(require('morgan')('dev')); app.use(express.urlencoded({ extended: false })); app.use(express.static(__dirname + '/public')); //app.use(layouts); const sessionObject = { secret: SECRET_SESSION, resave: false, saveUninitialized: true } app.use(session(sessionObject)); // Initialize passport and run through middleware app.use(passport.initialize()); app.use(passport.session()); // Flash // Using flash throughout app to send temp messages to user app.use(flash()); // Messages that will be accessible to every view app.use((req, res, next) => { // Before every route, we will attach a user to res.local res.locals.alerts = req.flash(); res.locals.currentUser = req.user; next(); }); app.get('/', (req, res) => { console.log(res.locals.alerts); res.render('index', { alerts: res.locals.alerts }); }); let city = Washington; const city = { method: 'GET', url: `https://www.numbeo.com/cost-of-living/in/${city}` } request(${newLocation}, (err, res, body) => { if (err) return console.error(err); let $ = cheerio.load(body); let title = $('tr').attr('class', 'first_currency'); let milkPrice = Number($('.first_currency').find('span').text().split('\n')[10].split('$')[0]); console.log(milkPrice); }); const PORT = process.env.PORT || 3000; app.get("/thing", (req, res) => res.send("Connected")); const server = app.listen(PORT, () => { console.log(`You are connected ${PORT} 🎧`); }); module.exports = server;
I am trying to have the interpolation populate with the city I want it to use, but when I use {city} is says its already defined.
➜ dev_jobs_usa git:(main) ✗ node index.js
/Users/carolinaurrea/Desktop/SEI1019/unit_two/deliverable/dev_jobs_usa/index.js:58
const {city} = {
^
SyntaxError: Identifier 'city' has already been declared
@canourrea23 you have city declared 2
times.
You can do this instead:
let city = Washington;
const requestObject = {
method: 'GET',
url: `https://www.numbeo.com/cost-of-living/in/${city}`
}
request(requestObject, (err, res, body) => {
if (err) return console.error(err);
let $ = cheerio.load(body);
let title = $('tr').attr('class', 'first_currency');
let milkPrice = Number($('.first_currency').find('span').text().split('\n')[10].split('$')[0]);
console.log(milkPrice);
});
city
and requestObject
will go@romebell
I keep on getting a SequelizeDatabaseError: column "userId" does not exist
when I try to post into my users profile. I have checked my associations. i'm not sure if I should try adding a joined table or maybe userWeather with attribute userid and weatherid.
This is the post route I am trying to use and the associations below it
router.post('/save',(req, res) => {
console.log('-----inside of post route for weather-----');
//Gets form data and add a new record to DB then redirect to my profile page
console.log('---THE OBJECT MY WEATHER---', req.body);
db.weather.findOrCreate({
where: { weather: req.body.city},
defaults:{
//icon: req.body.icon,
country: req.body.country,
description: req.body.description,
//main: req.body.main,
temperature: req.body.temperature,
feels_like: req.body.feels,
min_temp: req.body.min,
max_temp: req.body.max,
humidity: req.body.humidity}
}) .then(()=>{
res.redirect('/profile');
});
})
❓ ❓ ❓
static associate(models) {
// define association here
models.weather.belongsTo(models.user)
}
static associate(models) {
// define association here
models.user.hasMany(models.weather)
}
@romebell They are in 2 different models. The top one is in my weather model and the bottom one is in my user model.
@fmuwanguzi What does your model look like for each? Put them here...
@romebell They are in 2 different models. The top one is in my weather model and the bottom one is in my user model.
@fmuwanguzi What does your model look like for each? Put them here...
@romebell please see below
static associate(models) {
// define association here
models.weather.belongsTo(models.user)
}
};
weather.init({
city: DataTypes.STRING,
country: DataTypes.STRING,
description: DataTypes.STRING,
temperature: DataTypes.FLOAT,
feels_like: DataTypes.FLOAT,
min_temp: DataTypes.FLOAT,
max_temp: DataTypes.FLOAT,
humidity: DataTypes.INTEGER
}, {
sequelize,
modelName: 'weather',
});
return weather;
};
static associate(models) {
// define association here
models.user.hasMany(models.weather)
}
};
user.init({
name: {
type: DataTypes.STRING,
validate: {
len: {
args: [1,99],
msg: 'Name must be between 1 and 99 characters'
}
}
},
email: {
type: DataTypes.STRING,
validate: {
isEmail: {
msg: 'Invalid email'
}
}
},
password: {
type: DataTypes.STRING,
validate: {
len: {
args: [8,99],
msg: 'Password must be between 8 and 99 characters'
}
}
}
}, {
sequelize,
modelName: 'user',
});
user.addHook('beforeCreate', function(pendingUser) {
// Bcrypt hash a password for us
let hash = bcrypt.hashSync(pendingUser.password, 12);
// Set password to equal the hash
pendingUser.password = hash;
console.log(pendingUser);
});
user.prototype.validPassword = function(passwordTyped) {
let correctPassword = bcrypt.compareSync(passwordTyped, this.password);
console.log('Inside of validPassword', correctPassword);
// return true or false based on correct password or not
return correctPassword;
}
// Remove the password before it gets serialized
user.prototype.toJSON = function() {
console.log('Inside of the toJSON method');
let userData = this.get();
delete userData.password;
console.log(userData);
return userData;
}
return user;
};
@marjames98 go to my express_authentication repo and use that as a template. From there you will do the following:
what_to_cook
collaborator
what_to_cook
to your local machinenpm install
config.json
file
{
"development": {
"database": "what_to_cook_development",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"database": "what_to_cook_test",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"database": "what_to_cook_production",
"host": "127.0.0.1",
"dialect": "postgres"
}
}
database
called what_to_cook_development
inside of your terminalPut the command here... You can edit this message.
❓
router.get('/:id', (req,res) => {
const id = req.params.id
axios.get(`https://pokeapi.co/api/v2/pokemon/${id}/`)
.then(response => {
let pokemon = response.data;
console.log(pokemon)
{res.render('pokemon/show', { pokemon })}
})
profile.ejs
<ol>
<% const newLocation => { %>
<li>Washington: <% Washington %></li>
<li>New York: <% New-York %> </li>
<li>Los Angeles: <% Los-Angeles %></li>
<li>San Francisco: <% San-Francisco %></li>
<li>Seattle: <% Seattle %></li>
<li>Los-Angeles: <% Los-Angeles %></li>
<li>Chicago: <% Chicago %></li>
<li>Baltimore: <% Baltimore %> </li>
<li>Atlanta: <% 'Atlanta %> </li>
<li>Dallas: <% 'Dallas' %> </li>
<li>Austin: <% 'Austin' %> </li>
<% } %>
</ol>
@romebell step 7
@canourrea23
So i am thinking of doing something like this to get the city I want to populate. Am I on the right track? ❓
- How can we make this similar to what we want to build out?
- Is this where you're putting the scraping data?
response
- It's similar in that we are grabbing the name and inputting it to the end point.
- I want you to see the list of cities in your profile and click on the one you are interested in, get that information back and hopefully to be able to save that data if you choose to.
router.get('/:id', (req,res) => { const id = req.params.id axios.get(`https://pokeapi.co/api/v2/pokemon/${id}/`) .then(response => { let pokemon = response.data; console.log(pokemon) {res.render('pokemon/show', { pokemon })} })
profile.ejs
<ol> <% const newLocation => { %> <li>Washington: <% Washington %></li> <li>New York: <% New-York %> </li> <li>Los Angeles: <% Los-Angeles %></li> <li>San Francisco: <% San-Francisco %></li> <li>Seattle: <% Seattle %></li> <li>Los-Angeles: <% Los-Angeles %></li> <li>Chicago: <% Chicago %></li> <li>Baltimore: <% Baltimore %> </li> <li>Atlanta: <% 'Atlanta %> </li> <li>Dallas: <% 'Dallas' %> </li> <li>Austin: <% 'Austin' %> </li> <% } %> </ol>
app.get('/:city', async (req, res) => {
const city = req.params.city[0].toUpperCase() + req.params.city.slice(1).toLowerCase();
const { currency = 'CAD' } = req.query;
const response = await fetch(`https://www.numbeo.com/cost-of-living/in/${city}?displayCurrency=${currency}`);
if (!response.ok) {
return res.status(response.status).send(response.statusText);
}
const html = await response.text();
const $ = cheerio.load(html);
const rows = $('body > div.innerWidth > table > tbody > tr')
.filter((i, el) => $(el).children('td').length === 3)
.map((i, el) => $(el).children()
.map((i, el) => $(el).text().trim()).toArray())
.toArray();
});
@canourrea23
app.get('/:city', async (req, res) => {
const city = req.params.city[0].toUpperCase() + req.params.city.slice(1).toLowerCase();
console.log('CITY',city);
// const { currency = 'CAD' } = req.query;
console.log(req.query);
fetch(`https://www.numbeo.com/cost-of-living/in/${city}`, (error, meta, body) => {
let html = body.toString();
const $ = cheerio.load(html);
const priceRows = $('body > div.innerWidth > table.data_wide_table.new_bar_table > tbody > tr > td.priceValue > span.first_currency').text().split(' ');
console.log(priceRows);
})
});
@romebell
Every-time I try to create on my post route it updates the database but all the values of the object come out as null
router.post('/save', isLoggedIn, (req, res) => {
console.log('-----inside of post route for weather-----');
//Gets form data and add a new record to DB then redirect to my profile page
console.log('---THE OBJECT MY WEATHER---', req.body); //shows object
console.log(req.user.id, '----USER ID---') / shows user
db.weather.create({
where: { weather: req.body.city,
//id: req.body.id,
//icon: req.body.icon,
country: req.body.country,
description: req.body.description,
//main: req.body.main,
temperature: req.body.temperature,
feels_like: req.body.feels,
min_temp: req.body.min,
max_temp: req.body.max,
humidity: req.body.humidity}
})
.then((weather)=>{
console.log(weather.get()); //results are coming back as null
res.redirect('/profile');
});
})
I just see a [object:null prototype] when I console.log(req.body);
@canourrea23 parsedPriceRows
app.get('/:city', async (req, res) => {
const city = req.params.city[0].toUpperCase() + req.params.city.slice(1).toLowerCase();
console.log('CITY',city);
// const { currency = 'CAD' } = req.query;
console.log(req.query);
fetch(`https://www.numbeo.com/cost-of-living/in/${city}`, (error, meta, body) => {
let html = body.toString();
const $ = cheerio.load(html);
const priceRows = String($('body > div.innerWidth > table.data_wide_table.new_bar_table > tbody > tr > td.priceValue > span.first_currency').text().split(' ')[0]).split('$');
console.log(priceRows);
const parsedPriceRows = priceRows.map(element => {
if (element.includes(',')) {
let newPrice = Math.round(Number(element.replace(',', '')));
return newPrice;
} else {
let newPrice = Math.round(Number(element));
return newPrice;
}
});
console.log(parsedPriceRows[9])
const locationObject = {
bedroom_in_city: '',
bedroom_outside_centre: '',
public_transit: '',
internet: '',
childcare: '',
gas: '',
average_meal: '',
milk: '',
utilities: '',
}
});
const postArray = posts.map(post => {
return post.get();
})
console.log(postArray);
All you need to do is install the axios
library by saying:
npm i axios
From there inside of your server.js
file, you will need to require axios
at the top of your file:
const axios = require('axios');
Inside of your route, you can do:
axios.get('<endpoint>')
.then(response => {
console.log(response.data);
});
app.get('/:city', async (req, res) => {
const city = req.params.city[0].toUpperCase() + req.params.city.slice(1).toLowerCase();
console.log('CITY',city);
// const { currency = 'CAD' } = req.query;
console.log(req.query);
fetch(`https://www.numbeo.com/cost-of-living/in/${city}`, (error, meta, body) => {
let html = body.toString();
const $ = cheerio.load(html);
const priceRows = String($('body > div.innerWidth > table.data_wide_table.new_bar_table > tbody > tr > td.priceValue > span.first_currency').text().split(' ')[0]).split('$');
console.log(priceRows);
const parsedPriceRows = priceRows.map(element => {
if (element.includes(',')) {
let newPrice = Math.round(Number(element.replace(',', '')));
return newPrice;
} else {
let newPrice = Math.round(Number(element));
return newPrice;
}
});
console.log(parsedPriceRows[48])
const locationObject = {
bedroom_in_city: parsedPriceRows[47],
bedroom_outside_centre: parsedPriceRows[48],
public_transit: parsedPriceRows[28],
internet: parsedPriceRows[37],
childcare: parsedPriceRows[41],
gas: (parsedPriceRows[32]*3.785),
average_meal: parsedPriceRows[0],
milk: (parsedPriceRows[8]*3.785),
utilities: parsedPriceRows[35],
}
db.location.create(locationObject)
.then((newLocation) => {
console.log(newLocation.get());
res.render('city', { city, newLocation });
});
});
<!-- <ol> -->
<!-- <li>Bedroom In City: <%= location.bedroom_in_city %></li> -->
<!-- </ol> -->
<!-- <li>New York: <% New-York %> </li>
<li>Los Angeles: <% Los-Angeles %></li>
<li>San Francisco: <% San-Francisco %></li>
<li>Seattle: <% Seattle %></li>
<li>Los-Angeles: <% Los-Angeles %></li>
<li>Chicago: <% Chicago %></li>
<li>Baltimore: <% Baltimore %> </li>
<li>Atlanta: <% 'Atlanta %> </li>
<li>Dallas: <% 'Dallas' %> </li>
<li>Austin: <% 'Austin' %> </li> -->
@canourrea23
app.get('/:city', async (req, res) => {
const city = req.params.city[0].toUpperCase() + req.params.city.slice(1).toLowerCase();
fetch(`https://www.numbeo.com/cost-of-living/in/${city}`, (error, meta, body) => {
let html = body.toString();
const $ = cheerio.load(html);
const priceRows = String($('body > div.innerWidth > table.data_wide_table.new_bar_table > tbody > tr > td.priceValue > span.first_currency').text().split(' ')[0]).split('$');
const parsedPriceRows = priceRows.map(element => {
if (element.includes(',')) {
let newPrice = Math.round(Number(element.replace(',', '')));
return newPrice;
} else {
let newPrice = Math.round(Number(element));
return newPrice;
}
});
const locationObject = {
bedroom_in_city: parsedPriceRows[47],
bedroom_outside_centre: parsedPriceRows[48],
public_transit: parsedPriceRows[28],
internet: parsedPriceRows[37],
childcare: parsedPriceRows[41],
gas: (Math.round(parsedPriceRows[32]*3.785)),
average_meal: parsedPriceRows[0],
milk: (Math.round(parsedPriceRows[8]*3.785)),
utilities: parsedPriceRows[35],
}
db.location.create(locationObject)
.then(newLocation => {
console.log(newLocation.get());
// Carolina, make sure that you're getting back the new location before you send
// it to the ejs page.
res.render('city');
});
});
});
@fmuwanguzi You need to send the weather
up to the profile
page
.then((weather) => {
console.log(weather.get());
res.redirect('/profile', { weather: weather.get() });
});
Inside of your ejs
page, you can do the following:
<h3>Your places</h3>
<p><%= weather.city %></p>
<p><%= weather.description %></p>
<p><%= weather.temperature %></p>
<p><%= weather.feels_like %></p>
<p><%= weather.min_temp %></p>
<p><%= weather.max_temp %></p>
<p><%= weather.humidity %></p>
@canourrea23 Can you update your first couple lines to this....
// Modules
require('dotenv').config();
const express = require("express");
const cheerio = require('cheerio');
const request = require('request');
const layouts = require('express-ejs-layouts');
const session = require('express-session');
const passport = require('./config/ppConfig');
const flash = require('connect-flash');
const fetch = require('fetch').fetchUrl;
const db = require("./models");
const SECRET_SESSION = process.env.SECRET_SESSION;
const app = express();
const isLoggedIn = require('./middleware/isLoggedIn');
@fmuwanguzi You need to send the
weather
up to theprofile
page.then((weather) => { console.log(weather.get()); res.redirect('/profile', { weather: weather.get() }); });
Inside of your
ejs
page, you can do the following:<h3>Your places</h3> <p><%= weather.city %></p> <p><%= weather.description %></p> <p><%= weather.temperature %></p> <p><%= weather.feels_like %></p> <p><%= weather.min_temp %></p> <p><%= weather.max_temp %></p> <p><%= weather.humidity %></p>
@romebell so it renders it to another page weather/save. I am in the process of trying to to see what is being rendered so I can use findAll to display more than one place(added to saved) using a get route. It comes back mostly empty it does however show the user
Actually i figured this part out I know just need to have what I'm printing display correctly
Add your link to the ISSUE that you create here. Be sure to assign your Pod Leader