EditorJS not showing up? How to fix this? - node.js

I am creating a blog. Here I am using EditorJS as my blog-post editor. I am using nodejs, express and ejs. I can't see the EditorJS interface on my screen.
Here is my code.
code for app.js:
const express = require('express')
const app = express()
app.use(express.json())
app.set('view engine', 'ejs')
app.get('/', function(req, res) {
res.render('index.ejs')
})
app.listen(3000, function(){
console.log('Server is running on port 3000.')
})
code for index.ejs file:
<!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>Home | Editor JS</title>
</head>
<body>
<form action="/create-post" method="POST">
<label for="title">Title</label>
<input type="text" class="form-control" name="title" placeholder="Title" required>
<label for="content">Content</label>
<input type="text" id="editorjs" name="content" placeholder="Content" required>
<button type="submit">Create</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/#editorjs/editorjs#latest"></script>
<script>
const editor = new EditorJS('editorjs')
</script>
</body>
</html>
How to make the EditorJS interface to be appeared in the ejs file?

An error message would be helpful.
Did you start your express server? Your app.js seems to be missing app.listen(8080);
Also your app.get() call is missing the closing bracket.
The following code is working for me:
const express = require('express')
const app = express()
app.use(express.json())
app.set('view engine', 'ejs')
app.get('/', function(req, res) {
res.render('index.ejs')
})
app.listen(8080);
Did you install express and ejs correctly?
npm i -s ejs express
Also the view engine seems to expect your ejs-files to be in the "views" folder. When you open the page in your browser, you should see an error message if it is still not working.

After several researches I found that, instead of using <input id="editorjs"> if I use <div id="editorjs"></div>, EditorJS interface shows up.

Related

Can Not Get file EJS Under Views Directory

In this problem, I tried to render ejs after update the data from UI. Here is my code,
const express = require("express");
const bodyParse = require("body-parser");
const date = require(__dirname + "/date.js");
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(bodyParse.urlencoded({ extends: true }));
var path = require('path');
let items = ["Buy Food", "Cook Food", "Eat Food"];
let itemWorks = [];
app.get("/", function (req, res) {
let day = date.getDay();
res.render(path.join(__dirname + "/views/list.ejs"), { listTitle: day, listItem: items });
items.pop;
app.post("/", function (req, res) {
let item = req.body.foodservice;
if(res.body.list === "work"){
itemWorks.push(item);
res.redirect("/work");
}else{
items.push(item);
res.redirect("/");
}
items.push(item);
res.redirect("/");
});
});
Here is my list.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>To Do List</title>
</head>
<body>
<h1><%=listTitle%></h1>
<ul>
<% for(var i = 0; i < listItem.length; i++){ %>
<li><%=listItem[i]%></li>
<% } %>
</ul>
<form action="/" method="post">
<input type="text" name="foodservice" placeholder="New Item" autocomplete="off"/><br /><br />
<button type="submit" name="button" value=<%=listTitle%>>+</button>
</form>
</body>
</html>
Here is my project's structure:
BRANDNEW_PROJECT views /list.ejs app.js data.js
However, when I have executed it=> errors have been displayed as bellow
TypeError: Cannot read properties of undefined (reading 'list')
at E:\WEB DEVELOPMENT\NodeJS\BrandNew_Project\app.js:25:15
I have tried to debug by putting log to check whether it already points to file that I want or not and the path is correct and also to tried set up file path like this:
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
However, the issues have not been resolved.
What can be the reason here? Thanks a lot for your help.
Live working URL : https://stackblitz.com/edit/node-dmtquz?file=index.js
Views folder is default in EJS.
Concept:
when render html pages you must take care path will start for other inside views as root
when render html pages you must take care path will start for other inside views as root.
Not render views/layouts/index use layout/index because,EJS make views (or your directory) as active directory for it.
if you want to change the directory use app.set("views", path.join(path.resolve(), < dir name >)).
Structure:
views
-------- layouts
---------------- index.ejs (this file i rendered as root)
-------- partials
-----------------footer.ejs, header.ejs etc
Hope this will clear up your problem
var express = require("express");
var app = express();
// set the view engine to ejs
// app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
// use res.render to load up an ejs view file
// index page
app.get("/", function (req, res) {
res.render("layouts/index" , {
displayTitle: "items viewer",
item: ["item1", "item2"]
});
});
// about page
app.get("/about", function (req, res) {
res.render("layouts/about");
});
app.listen(8080);
console.log("Server is listening on port 8080");
<!-- root dir, views/layout/list.ejs -->
<!DOCTYPE html>
<html lang="en">
<body>
<%= displayTitle%>
<hr />
<% for (let i of items) { %>
<br />
<%= i %> <% } %>
</body>
</html>
I think you need to use path.resolve instead of path.join like this:
res.render(path.resolve(__dirname + "/views/list.ejs"), { listTitle: day, listItem: items });
You might also need to update your import of the date object at the top to use path.resolve like this:
const date = require(path.resolve(__dirname + "/date.js"));
In my code I use path.resolve anytime I use __dirname

script source not found, in node.js when trying https connection

im trying to reference socket.io in my login.html but it gives following error:
GET https://localhost:3000/socket.io.js net::ERR_ABORTED 404 (Not Found)
i think its because this code line in my login.html :
<script src='/client-dist/socket.io.js'></script>
i was trying other reference the script in other ways, but those doesnt work. it worked when my server.js was a http connection, but now i need a https connection.
its also dont possible to reference oder javascript refrences.
login.html:
<!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>Login</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<section>
<h1>Login</h1>
<p>
username:<input id="username">
<br>
password:<input id="password">
<br>
</p>
<p>
<button onclick="window.location.href='/register'">Create Account</button>
</p>
<button id="submitButtonLogin" onclick="onClick()">submit</button>
</section>
<script src='/client-dist/socket.io.js'></script>
</body>
</html>
server.js:
const express= require('express')
const app= express();
//const path= require('path')
const https= require('https')
const io=require('socket.io')(https,{maxHttpsBufferSize:1e8})
const fs=require('fs')
const sslServer =https.createServer({
key: fs.readFileSync('cert/key.pem'),
cert: fs.readFileSync('cert/cert.pem')
},app)
const PORT=process.env.PORT || 3000
sslServer.listen(PORT, ()=>{
console.log(`listening to port ${PORT}`)
});sslServer.setTimeout(0)
app.get('/test', (req,res)=>{
res.sendStatus(200);
})
app.use(express.static(__dirname + '/public'))
app.use(require('./routes/posts'));
app.use(require('./routes/users'));
app.get('/',(req,res)=>{
res.sendFile(__dirname + '/login_register/login.html')
})
app.get('/register',(req,res)=>{
res.sendFile(__dirname + '/login_register/register.html')
})
app.get('/chatroom',(req,res)=>{
res.sendFile(__dirname + '/index.html')
})
my hierarchy:
chatapplication
-cert
cert.pem
csr.pem
key.pem
-login_register
login.html
register.html
-model
user.js
-node_modules
(included when setup)
-public
client.js
style.css
-routes
users.js
database.js
index.html
package-lock.json
package.json
secret.json
server.js

Why passing JSON parameters from HTML to Node.js results in body parameter is undefined

I'm playing with Node.js for the first time trying to pass parameters from a form to my server and print them on the console
my html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Hello Node</title>
</head>
<body>
<h1> we have a website</h1>
<form action="/contact" enctype="application/json" method="POST">
<input name="firstName" placeholder="firstName" type="text" size="30" />
<input name="lastName" placeholder="lastName" type="text" size="30" />
<input name="submit" type="submit" value="Send This">
</form>
</body>
</html>
i've tried both with and without enctype="application/json"
my app.js file
const express = require('express');
const app = express();
const bodyParser = require('body-parser')
var jsonParser = bodyParser.json()
app.listen(3333, () => {
console.log("Server is up and listening on 3003"); //print to the server console (the terminal!!)
})
app.post("/contact", jsonParser, function (req, res) {
console.log("in /contact");
console.log("request body:" + req.body);
console.log("request body first name:" + req.body.firstName);
console.log("request query first name:" + req.query.firstName);
})
I've tried with and without app.use(bodyParser.json({ type: 'application/*+json' }))
Output:
[object Object]
request body first name:undefined
request query first name:undefined
According to Mozilla documentation application/json content type is not allowed to be set as enctype value, so you can either send json using javascript or add support for application/x-www-form-urlencoded via app.use(bodyParser.urlencoded({ extended: false }))

rendering in nodejs using express to html

I'm trying to get values from nodejs into HTML. I've seen lot of answers, but none of them is working.
here what I've done so far:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
</head>
<body>
<div>
<a id="test" name="test"> <%=name%></a>
</div>
</body>
</html>
app.js
const express =require('express')
const app = express();
var os = require( 'os' );
var path = require('path')
const PORT = process.env.PORT ||2000;
app.engine('html', require('ejs').renderFile);
app.get('/',(req,res)=>{
res.sendFile(path.join(__dirname+'/index.html'))
})
app.get('/test', (req, res)=> {
var name = 454;
res.render( "/index.html", {name:name});
});
app.listen(2001)
I don't get what I'm doing wrong. but it doesn't work as expected.
any idea how may I solve this ?
thanks in advance !
First, create a folder views and put your index.ejs right there (though, I am not sure, the extension have to be .ejs).
Then set the engine with:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
And change your routing to:
app.get('/', (req,res) => {
res.render('index', { name: 'Test' });
});
Edit: I have used the express application generator and also checked Using template engines with Express.
Edit: According to the extension .ejs:
One thing to note is that all files in which ejs syntax are used in
must be saved with a .ejs extension [...]
Taken from Using EJS as a Template Engine in your Express App, not from the official docs.

Angular.js (net::ERR_ABORTED 404 (Not Found))

MY server configuration file
const express=require('express');
const app = express();
const logger=require('./utils/logger');
const bodyParser=require('body-parser');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.set("view engine","ejs");
app.use('/', require('./Routes/sellerRoutes'));
app.listen(process.env.PORT||1234, (err)=>{
if(err) {
console.log('An Error has occured', err);
logger.error('Server Not Start ',err);
}
else {
console.log("Server Started");
logger.debug('Server Started');
}
})
My Routing file
const seller=require('express').Router();
const logger=require('../utils/logger');
const adminUser=require('../Models/Userclass');
const password=require('../Models/Passchange');
const operations=require('../db/Helpers/sellerOperations');
seller.post('/change',(req,res)=>{
console.log('kkkkkkkkkkkkkk');
res.render('change');
var newPass=req.body.newPass;
console.log("New Password:::",newPass);
var confirmPass=req.body.confirmPass;
console.log('Confirm Password:::',confirmPass);
var passPanel=new password(newPass,confirmPass);
var pr=operations.findOneAndUpdate(passPanel);
pr.then(data=>{
console.log(data);
res.render('change',{newPass:data.newPass, confirmPass:data.confirmPass});
})
})
seller.post('/submit',(req,res)=>{
res.render('submit');
});
module.exports=seller;
MY ejs (Template Engine) file
<body class="section">
<h1><center>Password Change</center></h1>
<form method="POST" action="submit">
<% var newPass;%> <% var confirmPass; %>
<label for="">New Password:</label>
<input type="password" id="newPass" name="newPass" value="<%=newPass%>">
<div class="cnfrm">
<label for="">Confirm Password:</label>
<input type="password" id="confirmPass" name="confirmPass" value="<%=confirmPass%>">
</div>
<button id="chngepswd" class="btn btn-success">OK</button></a>
</form>
<br>
</body>
My Controller.js file
const app=angular.module('app', []);
app.controller('adminctrl', ($scope,$http,$q)=>{
var newPass=$scope.newPass;
var confirmPass=$scope.confirmPass;
$scope.dochange()=function(){
$http.post('http://localhost:1234/user').then((data)=>{
let defered = $q.defer();
console.log(data);
defered.resolve(data);
}),then((err)=>{
console.log(err);
defered.reject(err);
})
return defered.promise;
}
})
Index.html File
<!DOCTYPE html>
<html lang="en" ng-app='app'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Document</title>
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../app.js"></script>
<script src="../js/controller.js""></script>
</head>
<style>
</style>
<body >
<div ng-controller="adminctrl">
<div>
<label for="">New Password</label>
<input type="text" name="newPass" id="newPass" ng-model="newPass">{{newPass}}<br>
<label for="">Confirm Password</label>
<input type="text" name="confirmPass" id="confirmPass" ng-model="confirmPass">{{confirmPass}}<br>
<button ng-click="dochange()">OK</button><br>
</div>
</div>
<br>
</body>
</html>
I am making the front end for my web application. I made index.html file in public folder and I have made an js folder in which I have an controller.js file. I have declared the source of .js file in script tag in HTML file.
But when I load the server it says controller is not found and I have installed bower package manager from which I have installed angular.js. My browser is not able to find neither the bower component in which there is my (angilar.min.js file) nor controller.js file.
It says
net::ERR_ABORTED 404 (Not Found) for every file and even for bower.

Resources