Uncaught ReferenceError: io is not defined at index 40 - node.js

var express= require("express")
var bodyParser=require("body-parser")
var app= express()
var http=require('http').Server(app)
var io=require('socket.io')(http)
app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
var messages=[
{name:"rohit",message:"hello"},
{name:"rohan",message:"hi"},
]
app.get('/messages', (req,res) =>{
res.send(messages)
})
app.post('/messages',(req,res)=>{
messages.push(req.body)
io.emit('message',req.body)
res.sendStatus(200)
})
io.on('connection',(socket)=>{
console.log('user connected')
})
var server= app.listen(3010, () => {
console.log("Server is listening on port ",server.address().port)
})
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script>src="http://localhost:3010/socket.io/socket.io.js"</script>
</head>
<body>
<div class="container">
<br>
<div class="jumbotron">
<h1 class="display-4">Send Message</h1>
<br>
<input id ="name" class="form-control" placeholder="Name">
<br>
<textarea id ="message" class="form-control" placeholder="Message"></textarea>
<br>
<button id="send" class="btn btn-success">Send</button>
</div>
<div id="messages">
</div>
</div>
<script>
var socket=io() <!--io is not defined pls help to resove this issue thnks in advance-->
$(()=> {
$("#send").click(() =>{
var message={name: $("#name").val(),message: $("#message").val()}
postMessage(message)
})
getMessages()
})
socket.on('message',addMessages)
function addMessage(message){
$("#messages").append(`<h4> ${message.name} </h4> <p> ${message.message} </p>`)
}
function getMessages(){
$.get("http://localhost:3010/messages",(data)=>{
data.forEach(addMessage);
})
}
function postMessage(message){
$.post("http://localhost:3010/messages",message)
}
</script>
</body>
</html>
This is the code for server.js and index.html respectively. My error:
io is not defined at index 40
I am new to node.js and try making a simple chat app. I know this is an error talked about a lot in here. But after a few posts found via google, it still didn't solve my problem.

use the CDN script
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>

Related

Login from a dropdown menu using MEAN stack

I'm new to learning the MEAN stack and I'm really confused. I'm trying to log in from a dropdown login menu I have created. However, I don't how and where to implement the endpoint. I have created a register page as well for a user to register and a home page. My goal is to login in from whichever page a user is using. For example, if he is on the home page, he would just click the Login dropdown menu, and then he would just log in. Is there any way I can accomplish that?
This is the app.js code
var express = require("express");
var bp = require("body-parser");
var mongo = require('mongodb').MongoClient;
var url = "mongodb://localhost/";
var app = express();
app.listen(8888, function(){console.log("Server is listening");});
app.use(express.static(__dirname));
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bp.urlencoded({extended : true}));
app.get("/register", function(req,res){
res.render('register');
});
var users = ['JonSnow8', 'Javascript29', 'User88'];
app.post("/register", function(req, res){
var firstname = req.body.firstname;
var lastname = req.body.lastname;
var email = req.body.email;
var password = req.body.password;
var login_email = req.body.login_email;
mongo.connect(url, function(err,db){
if(err){
console.log("Conenction failed");
}else{
console.log("Conenction succed");
var DB = db.db('a_db');
var user = pop(users);
//TODO: If user.isEmpty() then db.close();
var obj = {Firstname: firstname, Lastname : lastname, Username : user, Email : email, Password : password};
console.log(users)
DB.collection("test").insertOne(obj, function(err2, res){
if(err2){
console.log("error with DB");
throw err2;
}else{
console.log("inserted obj");
}
db.close();
});
}});
res.redirect('/register');
});
app.get("/home", function(req,res){
res.render('home');
});
function pop(array){
let i = (Math.random() * array.length) | 0 ;
return array.splice(i, 1)[0] ;
}
This is the Home.ejs page
<!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>Welcome</title>
<!-- CSS -->
<link rel="stylesheet" href="css/home.css">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
</head>
<body>
<div class="container-fluid parentContainer">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<p class="navbar-brand">Athens</p>
</div>
<ul class="d-flex nav-list">
<li class="nav-item">Home</li>
<li class="nav-item">Sights</li>
<li class="nav-item">Things to do</li>
<li class="nav-item">Reviews</li>
</ul>
<ul class="d-flex nav-list-lr">
<li class="nav-item drop" id="login-li">
Login
<div class="dropdown-menu" id="login-div">
<form class="form-horizontal" method="post" accept-charset="UTF-8">
<input class="form-control login" type="text" placeholder="Email" id="login-email" name="email"><br>
<input class="form-control login" type="password" placeholder="Password" id="login-password" name="password"><br>
<input class="btn btn-primary" id="login-btn" type="submit" name="submit" value="Login">
</form>
</div>
</li>
<li class="nav-item">Register</li>
</ul>
</div>
</nav>
<div class="intro-message">
<h1 class="message1">Visit Greece,</h1>
<h1 class="message2">Discover ATHENS</h1>
<h1 class="message3">Explore our city from here</h1>
</div>
</div>
</body>
</html>
P.S. Forgot to mention I am using MongoDB.

NotSameOriginAfterDefaultedToSameOriginByCoep issue on TinyMCE

I'm trying to embed tinyMCE to my project and having this issue from browser console while initializing TinyMCE.
GET https://cdn.tiny.cloud/1/vy3lklpfrj9a8l0jkefxe602pse728rb6ku0bqjf3i2cmqak/tinymce/5.10.3-128/themes/silver/theme.min.js net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep 200
and this
GET https://sp.tinymce.com/i?aid=vy3lklpfrj9a8l0jkefxe602pse728rb6ku0bqjf3i2cmqak&tna=tinymce_cloud&p=web&dtm=1646981257782&stm=1646981257782&tz=Asia%2FSeoul&e=se&se_ca=script_load net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep
I used script tag to add the TinyMCE...
with those errors, Nothing shows on the screen where textarea should be.
When I make an HTML file and open it with the browser, it has no problem.....
I'm trying this on localhost and I have localhost on approved domains list of TinyMCE's dashboard.
here's my code.
first, here's my entire EJS file
postWrite.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>My Blog</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
.nav-pills > .nav-item > .active {
color : white;
background-color : black;
}
</style>
<script src="https://cdn.tiny.cloud/1/(MY-API-KEY)/tinymce/5/tinymce.min.js" crossorigin="anonymous" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#mytextarea'
});
</script>
</head>
<body>
<header class="container">
<div class="d-flex flex-fill py-3 mb-4 border-bottom p-3">
<a href="/" class="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-decoration-none text-body">
<span class="fs-4 ms-3">HKJang's Blog</span>
</a>
<ul class="nav nav-pills">
<li class="nav-item"><a href="/" class="nav-link text-body" >About Me</a></li>
<li class="nav-item">Projects</li>
<li class="nav-item">Modify Index</li>
</ul>
<form class="col-12 col-lg-auto mb-3 mb-lg-0 me-lg-2">
<input type="search" class="form-control form-control-dark ms-3" placeholder="Search..." aria-label="Search">
</form>
<form>
<button class="btn btn-dark my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</header>
<main class="container">
<form method="post">
<textarea id="mytextarea">Hello, World!</textarea>
</form>
</main>
<footer class="container">
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
<script>
</script>
</body>
</html>
and the part that I'm having trouble on is
...
<script src="https://cdn.tiny.cloud/1/(MY-API-KEY)/tinymce/5/tinymce.min.js" crossorigin="anonymous" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#mytextarea'
});
</script>
...
...
<main class="container">
<form method="post">
<textarea id="mytextarea">Hello, World!</textarea>
</form>
</main>
...
this EJS file is rendered by controller.
projectController.js
const boardView = async(req, res) => {
res.render("boardView", {});
};
const postView = async(req, res) => {
res.render("postView", {});
};
const postWriteView = (req, res) => {
res.render("postWrite", {});
}
module.exports = {
boardView,
postView,
postWriteView
};
and finally, this is index.js file for my server
index.js
const express = require('express');
const app = express();
var bodyparser = require('body-parser');
const helmet = require('helmet');
const compression = require('compression');
const csp = require('helmet-csp');
const cors = require('cors');
app.use(bodyparser.json());
app.use(bodyparser.urlencoded({extended: true})); // bodyparser : post 방식 body parsing용 -> express 기본 탑재
app.use(express.json());
var corsOption = {
origin: 'localhost',
credentials:'true'
}
app.use(cors(corsOption));
app.use(helmet());
app.use(
csp({
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self' 'sha256-uts7zrnGYAKZNfvBc7PYcShvKP4t10vo5qemd5Yp0lc=' https://cdn.jsdelivr.net/"],
scriptSrc: ["'self' 'unsafe-inline' https://cdn.jsdelivr.net/ https://cdn.tiny.cloud/1/vy3lklpfrj9a8l0jkefxe602pse728rb6ku0bqjf3i2cmqak/tinymce/5/tinymce.min.js"],
imgSrc: ["'self' https://blogprojectbucket.s3.amazonaws.com/ https://blogprojectbucket.s3.ap-northeast-2.amazonaws.com"]
},
})
);
app.use(compression());
app.set('view engine', 'ejs');
//Routes
app.use('/', require('./routes/board'));
app.use('/api', require('./routes/api'));
app.use('/project', require('./routes/project'))
const PORT = process.env.PORT || 3000;
app.listen(PORT, console.log("Server start at port : "+PORT));
Btw, I've tried to open all CORS configuration by trying app.use(cors())
Please help!
So this is proper way to use TinyMCE if you're using an Express app:
https://www.tiny.cloud/docs/integrations/expressjs/
You have to npm install TinyMCE and use it.

Why is Multer req.file is undefined with this simple file upload?

Let me start off with :I've read through many similar topics, yet can't find the solution.
I just started a fresh react app, and copied the form from the express/multer documentation
<form action="http://localhost:5001/app-dev/us-central1/api/upload" encType="multipart/form-data" method="post">
<div className="form-group">
<input type="file" className="form-control-file" name="uploaded_file"></input>
<input type="text" className="form-control" placeholder="Number of speakers" name="nspeakers"></input>
<input type="submit" value="Get me the stats!" className="btn btn-default"></input>
</div>
</form>
And I have a firebase function running locally with an express app.
const upload = multer({dest: './'})
app.post('/upload', upload.single('uploaded_file'), function (req: any, res: any) {
console.log(req.file, req.body)
});
the request in the network call has these headers
req.file is undefined when logging.
Does anyone see the missing piece?
Thanks a lot
ps. I use the cors middleware to resolve CORS issues (& GET calls are working)
It should work. Here is a minimal working example:
app.js:
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: './' });
app.post('/app-dev/us-central1/api/upload', upload.single('uploaded_file'), function (req, res) {
console.log(req.file, req.body);
res.sendStatus(200);
});
app.listen(5001, () => console.log('Server started at http://localhost:5001'));
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="container">
</div>
<script type="text/babel">
(function () {
const e = React.createElement;
class Upload extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<form action="http://localhost:5001/app-dev/us-central1/api/upload" encType="multipart/form-data" method="post">
<div className="form-group">
<input type="file" className="form-control-file" name="uploaded_file"></input>
<input type="text" className="form-control" placeholder="Number of speakers" name="nspeakers"></input>
<input type="submit" value="Get me the stats!" className="btn btn-default"></input>
</div>
</form>
)
}
}
const domContainer = document.querySelector('#container');
ReactDOM.render(e(Upload), domContainer);
})()
</script>
</body>
</html>
Server logs:
Server started at http://localhost:5001
{ fieldname: 'uploaded_file',
originalname:
'Stack Exchange personalized prediction data 2020-12-21.json',
encoding: '7bit',
mimetype: 'application/json',
destination: './',
filename: 'af7fc0ae20d3404ada7273792db07dc9',
path: 'af7fc0ae20d3404ada7273792db07dc9',
size: 99765 } [Object: null prototype] { nspeakers: '23' }
Client logs:
npx http-server -p 3001 -c-1Starting up http-server, serving ./
Available on:
http://127.0.0.1:3001
http://192.168.31.128:3001
Hit CTRL-C to stop the server
source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/65308716

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.

req.body returns undefinded after setting bodyParser urlencoded to extended as false

I am a newbee to nodejs . I have tried to create simple chat App. The req.body in my app.post seems to return undefinded even after setting my body-parser urlencoded ({extented:false}).can anybody walk me through this?!..thanks in advance
here is my code server.js for server side:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(express.static(__dirname))
var messages = [
{name:'Brue',message:'Hello Diana'},
{name:'Diana', message:'Hey Bruce.'} ]
app.get('/messages', (req,res) => {
res.send(messages) })
app.post('/messages', (req,res) => {
messages.push(req.body)
res.sendStatus(200)})
var server = app.listen(8080, (err,data) => {
console.log('The server runs on the port:', server.address().port) })
here is my client side code:
<!DOCTYPE html> <html lang="en"> <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">
<title>Message App</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<br>
<div class="jumbotron">
<h1 class="display-4"> Send Message </h1>
<br>
<input class="form-control" type="text" placeholder="Name">
<br>
<textarea placeholder = "Message" class="form-control" id="mesage" cols="30" rows="10"></textarea>
<br>
<button id = "send" class="btn btn-success"> Send</button>
</div>
<div id="messages"></div>
</div>
<script>
$(() => {
$('#send').click(() => {
var message = { name: $("#name").val(), message: $("#message").val()}
postMessage(message)
})
getMessages() })
function addMessages(message){
$("#messages").append(`<h4>${message.name}</h4> <p> ${message.message} </p>`) }
function getMessages(){
$.get('http://localhost:8080/messages',(data) => {
data.forEach(addMessages); }) }
function postMessage(message){
$.post('http://localhost:8080/messages', message)
}
In your html, you misspelled your textarea's id. It is id="mesage" instead of id="message" with two 's'. And you never set the id of #name. Fix these.
<input class="form-control" id="name" type="text" placeholder="Name">
<textarea placeholder="Message" class="form-control" id="message" cols="30" rows="10"></textarea>
Makes sure that your variable, which u will send is valid. I recommend you to use the chrome debugger in these situations.

Resources