I am having trouble using the process.env to hide an api key. The process seems pretty straight forward, so I'm not really sure what's happening. If I plug the api key into the url it works, but when I use the .env variable it doesn't work. I've tried to console.log (process.env.WEATHER_API_KEY) and it comes up undefined.
I'm using JS, express, and node.
.env file:
WEATHER_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
app.js file:
require('dotenv').config();
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
const rp = require("request-promise");
let bodyParser = require("body-parser");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.get("/", (req, res) => {
res.render("index");
});
app.get("/results", (req, res) => {
let query = req.query.search;
let weatherApiKey = process.env.WEATHER_API_KEY;
let weatherUrl =
"https://api.openweathermap.org/data/2.5/weather?zip=" +
query +
"&appid=" +
weatherApiKey;
rp(weatherUrl)
.then((body) => {
let data = JSON.parse(body);
res.render("results", { data: data });
console.log("DOTENV", process.env.WEATHER_API_KEY);
})
.catch(err => {
console.log(err);
});
});
app.listen(PORT, () => {
console.log("Weather App is listening on PORT:", PORT);
});
Related
i created variable in app.post, and i want to use it in app.get, but before this i added this one to my database, but i don't know how to get access to this variable in other function, here is my code
const express = require("express");
const { default: mongoose } = require("mongoose");
const app = express();
const port = 3000;
const Task = require(`./models/task`);
require("./db/moongose");
// sendFile will go here
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.get("/task", (req, res) => {
res.render("../public/mainPage.ejs", {tasks: mongoose});
});
app.post("/task", async (req, res) => {
const task = new Task({
description: req.body.task,
});
try {
await task.save();
console.log(task.description);
res.redirect("/task");
} catch (e) {}
});
app.listen(port);
console.log("Server started at http://localhost:" + port);
and all i want to do is get acces to task.description in app.get
I'm building a e-commerce page using express and when i want to delete one of my products everything seems to work fine but the url doesn't change (and it should).
So here is my code:
//route
router.use('/product', require('./product.routes'))
router.delete('/item/:id', productController.deleteProduct);
//controller
deleteProduct: (req, res) => {
let id = req.params.id;
let newDatabase = database.filter((item) => item.id != id);
fs.writeFileSync(path.join(__dirname, '../database/productos.json'), JSON.stringify(newDatabase, null, 4), {encoding: 'utf-8'});
let productVisited = newDatabase.filter(item=>item.category=="visited");
let productInSale = newDatabase.filter(item=>item.category=="in-sale");
res.render("home", {newDatabase, productVisited, productInSale });
}
}
//EJS
<form method="POST" action="/product/item/<%= database.id %>?_method=DELETE">
<input type="submit" class="action-button delete" value="ELIMINAR">
</form>
//ENTRY POINT (APP.JS)
const express = require('express');
const path = require('path');
const methodOverride = require ('method-override');
const app = express();
app.use(express.static(path.join(__dirname, "./public")));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(methodOverride("_method"));
app.set("view engine", "ejs");
app.set("views",path.join(__dirname, "./src/views"));
app.use("/", require ("./src/routes/index.routes"));
app.use((req, res, next) => {
res.status(404).render('error')
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server Running')
})
Thanks in advance for your time! have a nice day
I want to make a redirect to another page if the data is inserted, but for some reason it does not work. please tell me how you can do this? there were different ways, but even argulatorjs didn't help.
let express = require("express");
let app = express();
let port = 3000;
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
let angular = require('angular');
let mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/test");
let nameSchema = new mongoose.Schema({
name: String,
login: String,
password: String,
authorization: Boolean
});
let User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
let myData = new User(req.body);
myData.save()
.then(item => {
res.send("Вы успешно зарегистрировались, перенаправление...");
$window.location.href = '/CA.html';
})
.catch(err => {
res.status(400).send("Что-то пошло не так");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});
You can use it in your end-point like this;
app.get('/stackoverflow', (req, res) => {
// Redirect goes to stackoverflow
res.redirect('https://stackoverflow.com/');
})
I've created simple Express.js Rest API with MongoDB. I am using this package: https://www.npmjs.com/package/api-query-params and everything works very well except for one thing. I have a URL like this:
localhost/properties/?town=LONDON
this returns all properties from London, the problem is with this is the next thing, I need to put capitalize value (LONDON), I am trying to achieve that this value can be lowercase (london), so final URL will be like this:
localhost/properties/?town=london
My route:
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
const aqp = require ('api-query-params');
router.get('/all', (req, res, next) => {
const { filter, skip, limit, sort, projection, population, casters } = aqp(req.query, {
casters: {
lowercase: val => req.query.toLowerCase(),
},
});
Property.find(filter)
.skip(skip)
.limit(limit)
.sort(sort)
.select(projection)
.populate(population)
.exec((err, properties) => {
if (err) {
return next(err);
}
res.send(properties);
});
});
module.exports = router;
And app.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
require('dotenv/config');
const mongoose = require('mongoose');
const propertyRoute = require('./routes/property');
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/properties', propertyRoute);
//routes
app.get('/', (req, res) => {
res.send('value');
});
mongoose.connect('linkdatabse', {
newUrlParser: true,
})
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
I've updated my route according to documentation: https://www.npmjs.com/package/api-query-params#add-custom-casting-functions
but still, this doesn't work
Can anybody try to help me with this, what am I doing wrong?
Attempting to use Axios.get method to get ':id'
S̶e̶r̶v̶e̶r̶ ̶i̶s̶ ̶r̶e̶s̶p̶o̶n̶d̶i̶n̶g̶ ̶w̶i̶t̶h̶ ̶a̶ ̶4̶0̶4̶
Currently I am unable to set the state of the component. I get an empty object
I've tried adjusting the controller parameters but cannot seem to figure it out
loadProfile() {
axios.get('http://localhost:3000/api/companies/' + this.props.match.params.id)
.then(res => {
if (!res) {
console.log("404 error, axios cannot get response");
} else {
console.log(res.data);
this.setState({ company: res.data });
}
});
express api route
companyRoutes.route('/:id').get(company_controller.company_id_get);
express controller
exports.company_id_get = (req, res) => {
const id = req.params.id;
Company.findById( id, (company, err) => {
if(err) {
console.log("404 error", err);
}
else {
res.json(company);
}
})
}
Server Side Code
'use strict';
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const passport = require('passport');
const app = express();
const users = require('./routes/api/users');
const companyRoute = require('./routes/api/companies');
app.use(express.static("static"));
//Bodyparser middleware
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB configuration
const db = require("./config.scripts/mongoKey").mongoURI;
// Connect to MonngoDB
mongoose.connect(
db, { useNewUrlParser: true }
)
.then((db) => console.log('MongoDB succesfully connected'))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
//Passport config
require('./config.scripts/passport.js')(passport);
//Routes
app.use('/api/users', users);
app.use('/api/companies', companyRoute);
//Redirect any server request back to index.html: To deal with CRS
app.get('/', function(req, res, next){
res.sendFile(path.join(__dirname, '../client', 'index.html'));
})
//Hostname and Port
//const hostname = '127.0.0.1';
const port = 3000;
app.listen(port, () => {
console.log(`Backend server is running at http://localhost:${port}/`);
});
An error that is showing up in the console/network and postman. It looks like the http.get request is being stalled
Seems you forgot a / in your route http:/localhost:3000/api/companies/.... Change it to http://... and that should fix your issue.