Displaying Contents of Mongodb Database on webpage - javascript

I am trying to display the contents of my database on a webpage.
The way I want to do it is by displaying the content in the database by descending order. I have made the connection to MongoDB and am able to see my data in the terminal stored correctly. I just can't seem to figure out how to display that stored data now.
Thanks!
Server.js file.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true })
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo");
var nameSchema = new mongoose.Schema({
Alert: String
});
var User = mongoose.model("User", nameSchema);
app.listen(3000, function() {
console.log('listening on 3000')
})
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.get('/alertview', (req, res) => {
res.sendFile(__dirname + '/alertview.html')
})
app.post('/', urlencodedParser, function (req, res) {
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
User.find({},function(err,docs){
console.log(docs);
})
Html file I want to display the alerts on.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="/alertpageStyle.css" media="screen" />
<meta charset="UTF-8">
<title>View Alerts</title>
</head>
<body>
<div class="header">
<h1>Current Alerts</h1>
</div>
</body>
</html>

Simple example using the EJS templating, essentially you pass your object to the template at the time of rendering. You can also iterate over data. Same approach can be used for Handlebars or Mustache packages.
var express = require('express');
var path = require('path');
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/', index);
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>

Related

Cast to ObjectId failed for value "XXXX" (type string) at path "_id" for model "XXXXX"

I have created a form that takes image url from user and stores it in MongoDB, but when I try to insert the link from the db via ejs the app crashes displaying this error " Cast to ObjectId failed for value "XXXX" (type string) at path "_id" for model "XXXXX" "
This problem appears only with the image, it works perfectly fine with anchor tags or other elements.
JavaScript
const express = require('express');
const path = require('path');
const ejs = require('ejs');
const ejsMate = require('ejs-mate');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const LandingPage = require('./models/landingpage')
const app = express();
mongoose.connect('mongodb://localhost:27017/landing-page', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
app.get('/',(req,res)=>{
res.render('index');
})
app.get('/create',(req,res)=>{
res.render('create');
})
app.post('/', async (req,res)=>{
const landingPage = new LandingPage(req.body.LandingPage);
landingPage.title = req.body.title;
landingPage.image = req.body.image;
landingPage.aflink = req.body.aflink;
landingPage.description = req.body.description;
await landingPage.save();
res.redirect(`/pages/${landingPage._id}`);
})
app.get('/pages',(req,res)=>{
res.render('pages');
})
app.get('/pages/:id', async (req,res)=>{
const {id} = req.params;
const landingPage = await LandingPage.findById(id);
res.render('landingpage',{landingPage});
})
app.listen('3000',()=>{
console.log('Listening on port 3000');
})
Html/ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1><%=landingPage.title%></h1>
<img src=" <%=landingPage.image%> " alt=""> // When I remove this line the app works again
Press here
<h2><%=landingPage.description%></h2>
</body>
</html>

using socket.io with express router

I am fairly new to node.js, I am trying to build a webchat and so far I have a server.js file and a router.js file that should have all my routes inside. I am not using express-generator. I would like to use socket.io but on my current setup it doesn't work.
Here is what I have
server.js
const path = require('path');
const express = require('express');
const layout = require('express-layout');
const app = express();
const routes = require('./router');
const bodyParser = require('body-parser');
var server = require('http').createServer(app);
var io=require('socket.io')(server);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
const middleware = [
layout(),
express.static(path.join(__dirname, 'public')),
bodyParser.urlencoded(),
];
app.use(middleware);
app.use('/', routes);
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
io.on('connection',function (socket) {
console.log('yo');
});
server.listen(3000, () => {
console.log(`App running at http://localhost:3000`);
});
router.js
const express = require('express');
const router = express.Router();
const {check, validationResult}=require('express-validator');
const { matchedData } = require('express-validator/filter')
const app = express();
router.get('/', (req, res) => {
res.render('index', {
data: {},
errors: {}
})
});
router.post('/enter', [
check('username')
.isLength({min: 1})
.withMessage('Username is required') //implement personalized check
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.render('index', {
data: req.body,
errors: errors.mapped()
})
}
const data = matchedData(req)
});
module.exports = router;
It should log "yo" on the console but it doesn't. I already tried to move the socket.io setup part to router.js, it doesn't give any errors but it does not log anything. Also if I set up correctly socket.io on my server.js, how do I pass it to router.js?
EDIT
there is the index.ejs file that has some client code that initializes the connection with socket.io
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Global.io</title>
<link type="text/css" rel="stylesheet" href="/index.css">
<script>
var socket = io();
socket.on('connect', function () { // TIP: you can avoid listening on `connect` and listen on events directly too!
console.log('yo client');
});
</script>
<!-- <script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/scripts/client.js" defer></script> -->
</head>
<body>
<h1>Start debating about the change</h1>
<div id="wrapper">
<form id="formElem" method="post" action="/enter" novalidate>
<% if (errors.username) { %>
<div class="error"><%= errors.username.msg %></div>
<% } %>
<input id='name' type="text" name="user" placeholder="User name" class=" <%= errors.username ? 'form-field-invalid' : ''%>">
<select name="room" id="room">
</select>
<button type="submit" id="submit-b">Submit</button>
</form>
</div>
</body>
</html>
Now it gives an error saying io is undefined.
You need this:
<script src="/socket.io/socket.io.js"></script>
Before the script that tries to use socket.io in your web page. That script loads the socket.io library and defines the io symbol so you can then use it after the library has been loaded.

Getting Cannot GET / in NodeJS Express project

I've tried numerous methods to solve this from app.use(express.static(__dirname + "public")) to res.render and it works in my terminal but not in my local host. Where am I going wrong?
Here's my JS file:
const express = require('express');
const bodyParser = require('body-parser');
var fs = require ('fs');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//
app.get('/index', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
//app.use(express.static(__dirname + '/public'));
//app.get('/index.html', (request, response) => response.sendFile( __dirname, "/index.html"));
app.post('/userinfo', (request, response) => {
const postBody = request.body;
console.log(postBody);
response.send(postBody);
});
app.listen(3002, () => console.info('Application running on port 3002'));
And here's my HTML file:
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Express - Node.js POST data example</title>
</head>
<body>
<form action="/userinfo" method="POST">
Some data: <input type="text" name="data" id="data">
<button type="submit">Send</button>
</form>
</body>
</html>
There is no response for base url or / route is defined. You have defined only two routes and I assume /index for your index page. So, the page will be render at localhost:3002/index . You have to define another response for / or base url like,
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
Hopefully, your problem will be solved.

Can't load static files in index.html

I'm trying setup simple app with node, express and angular2. The problem is that, when I run localhost, open it in browser, I get errors: "Uncaught SyntaxError: Unexpected token <". I think it happens because of incorrect path or wrong code in my node/express files.
For example, when I'm trying open library file in source, I always get index.html code :
Here is the folder structure:
Below I'll show full code
index.js
'use strict'
// require dependencies
let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
// require our custom dependencies
let router = require('./router');
let app = express();
const PORT = process.env.PORT || 4000;
// get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//share folder with static content
app.use(express.static(__dirname + '../frontend/build'));
app.use('/', router);
app.listen(PORT, function() {
console.log('Example app listening on port', PORT);
});
router.js
let express = require('express');
let router = express.Router();
let path = require('path');
let User = require('./models/user');
router.use(function(req, res, next) {
console.log('request to', req.path);
next();
});
router.route('/users')
.get(function(req, res) {
User.find(function(err, users) {
if (err) {
res.send(err);
}
res.json(users);
});
});
router.get('*', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
})
module.exports = router;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Angular 2 App!</title>
<base href="/">
<!-- load the dependencies -->
<script src="./assets/libs/core-js/client/shim.min.js"></script>
<script src="./assets/libs/zone.js/dist/zone.js"></script>
<script src="./assets/libs/reflect-metadata/Reflect.js"></script>
<script src="./assets/libs/systemjs/dist/system.src.js"></script>
<script src="./systemjs.config.js"></script>
<script>
System.import('app').catch(function(err) {
console.error(err);
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
Thanks!
Update
I changed in router.js from this
router.get('*', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
});
to this
router.get('/', function (req, res) {
res.status(200).sendFile(path.resolve('frontend/build/index.html'));
});
and now I have 404 error, files not found

Vue-resource can't load express static file

So, I have a bit of a problem. Here's my server.js
require('dotenv').load();
const http = require('http');
const path = require('path');
const express = require('express');
const app = express();
const server = http.createServer(app).listen(8080, () => {
console.log('Foliage started on port 8080');
});
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
What this does, is that for every /whatever it gives the index.html file. Alongside that, it serves static files from /public Now, my index.html looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Foliage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/foliage.css" media="screen" title="no title">
<script src="https://use.fontawesome.com/763cbc8ede.js"></script>
</head>
<body>
<div id="app">
<router-view :key="$router.currentRoute.path"></router-view>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="js/md5.js"></script>
<script src="js/cookies.js"></script>
<script src="js/dragula.js"></script>
<script src="js/build.js"></script>
</body>
</html>
All of the JS files and the style files are loaded appropriately from public/jsand public/css for this. However, in build.js, which is a webpack-ed vuejs app, I use vue-resource, to load in another file from public/themes/Bareren/templates. That looks like this
page = {};
page.Template = "Index";
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response) => {
console.log(response.body);
});
However, this request does not give me the file in public/themes/Barren/templates. It instead gives back the site's own index.html file. How could i fix this?
app.use(express.static(path.join(__dirname, '/public')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); });
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html')); });
Try to console.log(path.join(__dirname, '/public')) and console.log(path.join(__dirname, 'index.html') to see if the path matches what you are expecting.
this.$http.get('themes/Barren/templates/'+page.Template+'.html').then((response)
=> {
console.log(response.body); });
You can also try console logging your get request. Usually I need to play with the pathing to making sure I'm serving the correct files.
One thing you can try is to define a GET route which responds with your template before the wildcard at the bottom.
app.get('/themes', (req, res) => {
// get the theme name
res.sendFile(path.join(__dirname, ... ));
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});

Categories

Resources