I want to add a second route to a /privacy page, but it is not working. I get "Cannot GET /privacy.html" error. Any suggestions??
This code does not respond with the privacy.html content
app.get('/privacy', function(req, res) {
res.sendFile(__dirname + "/privacy.html");
});
Here is my app.js code
//jshuint esversion: 6
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.get('/privacy', function(req, res) {
res.sendFile(__dirname + "/privacy.html");
});
app.post("/", function(req, res) {
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const emailAddress = req.body.emailAddress;
const data = {
members: [
{
email_address: emailAddress,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}
]
};
const jsonData = JSON.stringify(data);
const url = "https://us.api.mailchimp.com/3.0/lists/bb80b745a8"
const options = {
method: "POST",
auth: "meshiaR:93d648-u"
};
const request = https.request(url, options, function(response) {
if (response.statusCode === 200) {
res.sendFile(__dirname + "/success.html");
} else {
res.sendFile(__dirname + "/failure.html");
}
response.on("data", function(data){
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
});
// app.post("/privacy", function(req, res){
// res.sendFile(__dirname + "/privacy.html");
// });
app.post("/failure", function(req, res) {
res.redirect("/");
});
app.listen(process.env.PORT || 3000, function(){
console.log("Server is now running on port 3000");
});
This is how I achieve this kind of tasks.
var path = require('path');
app.get('/privacy', function(req, res) {
res.sendFile(path.join(__dirname + '/privacy.html'));
});
BTW, check your privacy.html is available in correct path.
Related
I have been getting the above error and I have been looking for a solution for days,I don't know what have I done wrong.Basically I want to send the success page if the response code corresponds to 200 from my API, if not send the failure page. Here is my code.
'''
const express = require('express');
const app= express();
const bodyParser = require('body-parser');
const request = require('request');
const https = require('https');
const port = 3000;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/signup.html');
});
app.post('/', function(req, res){
const fname = req.body.fName;
const lname = req.body.lName;
const email = req.body.email;
res.write(fname);
res.write(lname);
res.write(email);
const data = {
members: [
{
email_address:email,
status: 'subscribed',
merge_fields:{
FNAME: fname,
LNAME: lname
}
}
]
};
const jsonData = JSON.stringify(data);
const url = 'https://us6.api.mailchimp.com/3.0/lists/listId'
const options = {
method: 'POST',
auth:'nhlanhla:API Key'
};
const request = https.request(url, options, function(response){
if(response.statusCode===200){
res.sendFile(__dirname + '/success.html');
}else{
res.sendFile(__dirname + 'failure.html');
}
response.on('data', function(data){
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end()
});
app.post('/failure', function(req, res){
res.redirect('/');
});
app.listen(port, function(req, res){
console.log('The server has started');
});
'''
Your request.end() is being called before you complete your API call to https://us6.api.mailchimp.com finishes.
I'm guessing you only need to send success.html or failure.html based on the result to the API call to https://us6.api.mailchimp.com.
If that so, update your code like below:
app.post('/', function(req, res){
const fname = req.body.fName;
const lname = req.body.lName;
const email = req.body.email;
// res.write(fname);
// res.write(lname);
// res.write(email);
const data = {
members: [
{
email_address:email,
status: 'subscribed',
merge_fields:{
FNAME: fname,
LNAME: lname
}
}
]
};
const jsonData = JSON.stringify(data);
const url = 'https://us6.api.mailchimp.com/3.0/lists/listId'
const options = {
method: 'POST',
auth:'nhlanhla:API Key'
};
https.request(url, options, function(response){
if(response.statusCode===200){
res.sendFile(__dirname + '/success.html');
}else{
res.sendFile(__dirname + 'failure.html');
}
response.on('data', function(data){
console.log(JSON.parse(data));
});
});
// request.write(jsonData);
// request.end()
});
Use promises to solve your problem
makeRequest(url, options) {
return new Promise((resolve, reject) => {
https.request(url, options, function(response){
if(response.statusCode===200){
// better resolve here, unless you need data
// resolve(response.statusCode);
}else{
reject(response.statusCode);
}
response.on('data', function(data){
resolve(JSON.parse(data));
});
});
});
}
and use it
var jsonData;
try {
jsonData = await makeRequest(url, options);
res.sendFile(__dirname + '/success.html');
} catch(err){
res.sendFile(__dirname + 'failure.html')
}
request.write(jsonData);
request.end()
What I am trying to do is simple training server app with CRUD functions.
I succeeded with that I can edit or delete already existing users, but stuck on trying to solve how actually to create and add to existing users.json file another one. I am sure that I am missing something.
Git repo for full directory: https://gitlab.com/alexgnatrow/practice-nodejs
Here is the main index.js.
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const engines = require('consolidate');
const bodyParser = require('body-parser');
let users = [];
function getUser(username) {
let user = JSON.parse(fs.readFileSync(getUserFilePath(username), {encoding: 'utf8'}));
user.nickname = user.name.toLowerCase().replace(/\s/ig, '');
return user
}
function getUserFilePath(username) {
return `${path.join(__dirname, 'users', username)}.json`
}
function createUser(username, data){
let fp = getUserFilePath(username);
let string = JSON.stringify(data, null , 2);
console.log(string);
fs.writeFileSync(fp, string , {encoding: 'utf8'})
}
function saveUser(username, data) {
let fp = getUserFilePath(username);
fs.unlinkSync(fp);
console.log(data);
fs.writeFileSync(fp, JSON.stringify(data, null, 2), {encoding: 'utf8'})
}
function verifyUser(req, res, next) {
let username = req.params.username;
let fp = getUserFilePath(username);
fs.exists(fp, yes => {
if (yes) {
next()
} else {
res.redirect('/error/' + username)
}
})
}
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');
app.use(express.static('public')); //example of serve static files
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json()); // Body parser use JSON data
app.get('/', (req, res) => {
fs.readdir('users', (err, files) => {
if(err|| files==="favicon.ico"){console.log('there is no need to create a fucking favicon');}
files = _.filter(files, file => !file.startsWith('.'));
users = _.map(files, file => getUser(file.replace(/\.json/ig, '')));
res.render('index', {users})
});
});
app.get('*.json', (req, res) => res.download('./users/' + req.path));
app.get('/error/:username', (req, res) => res.status(404).send(`No user named ${req.params.username} found`));
app.get('/data/:username', (req, res) => {
res.header("Content-Type", 'application/json');
res.send(JSON.stringify(getUser(req.params.username), null, 4));
});
app.all('/:username', function(req, res, next) {
console.log(req.method, 'for', req.params.username);
next()
});
app.get('/:username', verifyUser, function(req, res) {
const user = getUser(req.params.username);
res.render('user', {user, address: user.location})
});
app.post('/', (req,res) => {
createUser(req.params.name, req.body);
console.log(req.body);
res.end()
});
app.put('/:username', function(req, res) {
saveUser(req.params.username, req.body);
res.end()
});
app.delete('/:username', function(req, res) {
fs.unlinkSync(getUserFilePath(req.params.username)); // delete the file
res.sendStatus(200)
});
const server = app.listen(3000, function() {
console.log('Server running at http://localhost:' + server.address().port)
});
the index.hbs with html page where i am trying to add a user:
const express = require('express');
const app = express();
const path = require('path');
const fs = require('fs');
const _ = require('lodash');
const engines = require('consolidate');
const bodyParser = require('body-parser');
let users = [];
function getUser(username) {
let user = JSON.parse(fs.readFileSync(getUserFilePath(username), {encoding: 'utf8'}));
user.nickname = user.name.toLowerCase().replace(/\s/ig, '');
return user
}
function getUserFilePath(username) {
return `${path.join(__dirname, 'users', username)}.json`
}
function createUser(username, data){
let fp = getUserFilePath(username);
let string = JSON.stringify(data, null , 2);
console.log(string);
fs.writeFileSync(fp, string , {encoding: 'utf8'})
}
function saveUser(username, data) {
let fp = getUserFilePath(username);
fs.unlinkSync(fp);
console.log(data);
fs.writeFileSync(fp, JSON.stringify(data, null, 2), {encoding: 'utf8'})
}
function verifyUser(req, res, next) {
let username = req.params.username;
let fp = getUserFilePath(username);
fs.exists(fp, yes => {
if (yes) {
next()
} else {
res.redirect('/error/' + username)
}
})
}
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');
app.use(express.static('public')); //example of serve static files
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json()); // Body parser use JSON data
app.get('/', (req, res) => {
fs.readdir('users', (err, files) => {
if(err|| files==="favicon.ico"){console.log('there is no need to create a favicon');}
files = _.filter(files, file => !file.startsWith('.'));
users = _.map(files, file => getUser(file.replace(/\.json/ig, '')));
res.render('index', {users})
});
});
app.get('*.json', (req, res) => res.download('./users/' + req.path));
app.get('/error/:username', (req, res) => res.status(404).send(`No user named ${req.params.username} found`));
app.get('/data/:username', (req, res) => {
res.header("Content-Type", 'application/json');
res.send(JSON.stringify(getUser(req.params.username), null, 4));
});
app.all('/:username', function(req, res, next) {
console.log(req.method, 'for', req.params.username);
next()
});
app.get('/:username', verifyUser, function(req, res) {
const user = getUser(req.params.username);
res.render('user', {user, address: user.location})
});
app.post('/', (req,res) => {
createUser(req.params.name, req.body);
console.log(req.body);
res.end()
});
app.put('/:username', function(req, res) {
saveUser(req.params.username, req.body);
res.end()
});
app.delete('/:username', function(req, res) {
fs.unlinkSync(getUserFilePath(req.params.username)); // delete the file
res.sendStatus(200)
});
const server = app.listen(3000, function() {
console.log('Server running at http://localhost:' + server.address().port)
});
the error log
Server running at http://localhost:3000
TypeError: Path must be a string. Received undefined
at assertPath (path.js:28:11)
at Object.join (path.js:501:7)
at getUserFilePath (C:\Users\Лёша\jsDir\practice-nodejs\index.js:21:20)
at createUser (C:\Users\Лёша\jsDir\practice-nodejs\index.js:25:14)
at app.post (C:\Users\Лёша\jsDir\practice-nodejs\index.js:88:5)
at Layer.handle [as handle_request] (C:\Users\Лёша\jsDir\practice-nodejs\nod
e_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\lib\router
\route.js:137:13)
at Route.dispatch (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\
lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\Лёша\jsDir\practice-nodejs\nod
e_modules\express\lib\router\layer.js:95:5)
at C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\lib\router\index
.js:281:22
at Function.process_params (C:\Users\Лёша\jsDir\practice-nodejs\node_modules
\express\lib\router\index.js:335:12)
at next (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\lib\router
\index.js:275:10)
at C:\Users\Лёша\jsDir\practice-nodejs\node_modules\body-parser\lib\read.js:
130:5
at invokeCallback (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\raw-body
\index.js:224:16)
at done (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\raw-body\index.js:
213:7)
at IncomingMessage.onEnd (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\r
aw-body\index.js:273:7)
In this chunk of code, req.params.name is undefined :
app.post('/', (req,res) => {
createUser(req.params.name, req.body);
console.log(req.body);
res.end()
});
req.params are the parameters passed to a route. (eg. /:name)
Perhaps you meant req.body (the JSON body in the POST payload)?
app.post('/', (req,res) => {
createUser(req.body.name, req.body);
console.log(req.body);
res.end()
});
I need to understand how flow works in an Express app using Routes,
I have These Routes
app.use(require('./routes/reportsRouter'));
app.use(require('./routes/crewsRouter'));
app.use(require('./routes/api'));
app.use(require('./routes/filesRouter'));
Now in ./routes/crewsRouter I have th following Code
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
var url = req.url;
//..... Edit URL if Contains // empty parm
// crews//today; correct Url crews/all/today
// this give me a list of all jobs for all crews for today.
console.log("CrewsRouter: ", req.method + ".( " + url + " )");
next();
});
router.get('/crews', function(req, res) {
if (!req.params.key) { next(); }
res.render('crewsView',{
pageTitle:'All-Crews',
pageID:'crews',
crewInfo: {"aka": "all"},
reqOptions: ''
});
});
router.get('/crews/:leadId?/:options?', function(req, res) {....}
module.exports = router;
and in reportsRouter.js
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
// log each request to the console
console.log("ReportsRouter: ", req.method + ".( " + req.url + " )");
// continue doing what we were doing and go to the route
next();
});
router.get('/reports', function(req, res) {
//var data = req.app.get('appData')
res.render('reportsView',{
pageTitle:'Reports',
pageID:'reports'
});
});
module.exports = router;
The behavior I'm having is no matter what route I request
both of the route.use is running. Is this normal and what can i do to stop this behavior.
let crewsRouter = require('routes/crewsRouter');
...
app.use('/crews', crewsRouter);
app.use('/reports', reportsRouter);
# crews
...
router.get('/', function(req, res) {
... # this used to be your '/crews' handler
}
# reports
...
router.get('/', function(req, res) {
... # this used to be your '/reports' handler
}
You should probably be doing something like this:
app.use('/reports', require('./routes/reportsRouter'));
app.use('/crews', require('./routes/crewsRouter'));
app.use('/api', require('./routes/api'));
app.use('/files', require('./routes/filesRouter'));
And then in your reportsRouter:
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
// log each request to the console
console.log("ReportsRouter: ", req.method + ".( " + req.url + " )");
// continue doing what we were doing and go to the route
next();
});
router.get('/', function(req, res) {
//var data = req.app.get('appData')
res.render('reportsView',{
pageTitle:'Reports',
pageID:'reports'
});
});
module.exports = router;
And your crewsRouter:
var express = require('express');
var router = express.Router();
router.use(function(req, res, next) {
var url = req.url;
//..... Edit URL if Contains // empty parm
// crews//today; correct Url crews/all/today
// this give me a list of all jobs for all crews for today.
console.log("CrewsRouter: ", req.method + ".( " + url + " )");
next();
});
router.get('/', function(req, res) {
if (!req.params.key) { return next(); }
res.render('crewsView',{
pageTitle:'All-Crews',
pageID:'crews',
crewInfo: {"aka": "all"},
reqOptions: ''
});
});
router.get('/:leadId?/:options?', function(req, res) {....});
module.exports = router;
My get and post APIs are working, but for some reason my app.put isn't.
When I hit localhost:3001/contacts/1 as a PUT in PostMan, I don't even see my simple console.log:
app.put('/api/contacts:id', (req, res) => {
console.log('req.params.id', req.params.id);
res.json(contact);
});
app.put
app.put('/api/contacts:id', (req, res) => {
console.log('req.params.id', req.params.id);
res.json(contact);
});
Full server.js code
// Requires ////////////////////////////////////////////////////////////////////
const express = require('express');
const app = express();
const bodyParser = require('body-parser'); // req.body
const cors = require('cors');
const R = require('ramda');
// Variables ///////////////////////////////////////////////////////////////////
const hostname = 'localhost';
const port = 3001;
let contacts = require('./data');
// Logic ///////////////////////////////////////////////////////////////////////
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/api/contacts', (req, res) => {
if (!contacts || R.isEmpty(contacts)) returnError(res, 'No Contacts found');
res.json(contacts);
});
app.get('/api/contacts/:id', (req, res) => {
const contact = contacts.filter(contact => contact.id == req.params.id);
if (R.isEmpty(contact)) returnError(res, 'No Contact found');
res.json(R.head(contact));
});
app.post('/api/contacts', (req, res) => {
const contact = {
id: contacts.length + 1,
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
website: req.body.website
}
contacts.push(contact);
res.json(contact);
});
app.put('/api/contacts:id', (req, res) => {
console.log('req.params.id', req.params.id);
// const contact = contacts.filter(contact => {
// return contact.id == req.params.id
// })[0];
// console.log('1 contact', contact);
// const index = contacts.indexOf(contact);
// const keys = Object.keys(req.body);
// keys.forEach(key => {
// contact[key] = req.body[key];
// });
// console.log('2 contact', contact);
// contacts[index] = contact;
// console.log('contacts', contacts);
// res.json(contacts[index]);
res.json(contact);
});
const returnError = (res, msg) => res.status(404).json({ message: msg });
app.listen(port, hostname, () => {
console.log(`server is running at http://${hostname}:${port}`);
});
Looks like a typo in this line:
app.put('/api/contacts:id', (req, res) => {
Add a '/' to read:
app.put('/api/contacts/:id', (req, res) => {
Your URL looks like this:
app.put('/api/contacts:id', (req, res) => {,
But it should be like this:
app.put('/api/contacts/:id', (req, res) => {
I have an express.js app that get to this:
node app.js
info - socket.io started
And it won't get any further, if anyone can explain why this happens and how to fix it, it would be greatly appreciated. I believe the error is in my app.js which is posted here:
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var http = require('http');
var db = mongojs('127.0.0.1:27017/mySpendingDB', ['users']);
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var path = require('path');
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/', function (req, res) {
res.render('login.html', {
title: 'Login'
});
});
app.get('/index', function (req, res) {
res.render('index.html', {
title: 'Daily'
});
});
app.get('/monthly', function (req, res) {
res.render('monthly.html', {
title: 'Monthly'
});
});
app.get('/yearly', function (req, res) {
res.render('yearly.html', {
title: 'Login'
});
});
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
var user = "";
io.sockets.on('connection', function (socket) {
console.log('socket.io started');
socket.on('login', function (data) {
var checkUser = db.users.find(data);
if (checkUser !== null) {
user = checkUser.username;
app.get('/index', function (req, res) {
res.direct('/index');
});
socket.emit('uploadList', checkUser.total);
}
});
socket.on('purchaseLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.purchase.save(data);
});
socket.on('depositLog', function (data) {
var usercollection = db.users.find({
username: user
});
usercollection.deposit.save(data);
});
socket.on('goLogout', function (data) {
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
});
socket.on('goIndex', function (data) {
app.get('/index', function (req, res) {
res.redirect('/index');
});
});
socket.on('goMonthly', function (data) {
app.get('/monthly', function (req, res) {
res.redirect('/monthly');
});
var monTot = db.users.find({
username: user
}).monthlyTotal;
socket.emit('wentMonthly', monTot);
});
socket.on('goYearly', function (data) {
app.get('/index', function (req, res) {
res.redirect('/index');
});
var yearTot = db.users.find({
username: user
}).yearlyTotal;
socket.emit('wentYearly', yearTot);
});
socket.on('registered', function (data) {
db.users.save(data);
app.get('/index', function (req, res) {
res.redirect('/index');
});
});
});
app.listen(3000);
You should be using server.listen(port) instead of app.listen(port). Using app.listen() will only start your Express application, while you also want the HTTP server that socket.io is piggybacking on to start.