I have the following app with express/socket.io (the app is listening and live without any errors). When I http-request it I get the following error:
GET http://localhost:3030/socket.io/1/?t=1630097351846 404 (Not Found)
And on the socket.io reponse http://localhost:3030/socket.io at I get:
Cannot GET /socket.io
Please help !!
const socket=io.connect('http://localhost:3030/');
//const { Socket } = require("socket.io");
const videoGrid=document.getElementById('video-grid');
const myVideo=document.createElement('video');
myVideo.muted=true;
let myVideoStream
navigator.mediaDevices.getUserMedia({
video:true,
audio:true
}).then(stream=>{
myVideoStream=stream;
addVideoStream(myVideo,stream);
})
// socket.emit('join-room');
const addVideoStream=(video,stream)=>{
video.srcObject=stream;
video.addEventListener('loadedmetadata',()=>{
video.play();
})
videoGrid.append(video);
}
const express=require('express');
const app=express();
const server=require('http').Server(app);
const {v4: uuidv4}= require('uuid');
const io=require('socket.io-client')(server);
//import { io } from "socket.io-client";
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/',(req,res)=>{
res.redirect(`/${uuidv4()}`);
})
app.get('/:room',(req,res)=>{
res.render('room',{roomId :req.params.room});
})
io.on('connection',socket=>{
socket.on('join-room',()=>{
console.log("Room Joined");
})
})
//now need to import socket.io in script.js
// server.listen(app.get('3030'));
app.listen(3030);
<!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>Zoom RJ</title>
<link rel="stylesheet" href="style.css">
<script src="http://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>
<!-- <script src="/node_modules/socket.io/client-dist/socket.io.js"></script> -->
</head>
<body>
<div id="video-grid">
</div>
<script src="script.js"></script>
</body>
</html>
Related
I have an electron app where i use preact package to create components and serve them in an index.html and i want to turn it to a web app
my file structure is
-- src/
---- workers/
---- components/
---- index.js (rendering the div#root)
-- index.html (with div#root and script src='src/index.js')
the js files contain nodejs code
i tried to create a root file index.js with a server pointing to index.html but the js inside src/ doesn't work
index.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>title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="root"></div>
<script src="./src/index.js"></script>
</body>
</html>
src/index.js:
const { render, h } = require("preact");
const App = require("./components/App");
const rootEl = document.getElementById("root");
render(h(App, { rootEl }), rootEl);
i tried this:
const path = require("path");
const express = require("express");
const app = express();
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.listen(process.env.PORT || 4433, () => {});
I keep getting the following MIME error while trying to lead in a stylesheet to my application:
I have followed the newest issues on this MIME error for hours now with no luck. I have told my Express development server to pull resource from a static file and still no luck. Here is my development hierarchy:
I will include my code below. Any help is appreciated.
**index.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">
<meta name="description" content="">
<meta name="subject" content="">
<meta name="author" content="">
<link rel="stylesheet" href="/public/styles/customStyles.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<title>Clone Application</title>
</head>
<body>
<div class="conatiner-fluid">
<nav class="nav-wrapper">
Hello Again
</nav>
Hello World
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</body>
</html>
**Server.js**
const express = require('express');
const app = express();
const router = require("./router");
const path = require("path");
const PORT = 3000;
app.use(router, express.static('public'));
app.listen(PORT, () => {
console.log("Listening on port: " + PORT);
});
**router.js**
const express = require('express');
const router = express.Router();
const pages = "/public/pages/";
router.get('/home', (req, res) => {
res.sendFile(__dirname + "/public/pages/home/index.html")
})
module.exports = router;
Your HTML links to the stylesheet at /public/styles/customStyles.css
However, the correct URI is /styles/customStyles.css (or preferably without the first slash, styles/customStyles.css so it will continue to work if the page isn't in the root).
app.use(router, express.static('public')); tells express to serve static files under the 'public' folder, so adding 'public' to your CSS URI is incorrect.
You're getting an HTML MIME type due to the Express default error page ('Cannot GET..')
Losing my mind here. I feel like I have the paths correct but for some reason my script file isn't loading/working. When I move the code to the app.js it prints out what I want to the console and works just fine but when I have it in the scripts file, it does nothing. I cant seem to find the problem.
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(express.static(`${__dirname}/public`));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
const rootRoute = require('./routes/index')
app.use('/', rootRoute);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log('server is running')
});
HTML page
<!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>In Your Words</title>
<link rel="stylesheet" href="/stylesheets/app.css">
</head>
<body>
<script type="text/javascript" src="/scripts/logic.js"></script>
</body>
</html>
script page
const generateInputs = () => {
let randomNumber = Math.floor(Math.random() * 20);
console.log(randomNumber)
}
generateInputs();
I need to pass a variable from a NodeJS file to a rendered html file. How to do that?
Here below what I had tried
Nodejs code
const loginRouter= express.Router();
const config= require('../config/config.json');
loginRouter.get('/', (req,res)=>{
res.render(path.dirname(__dirname)+'/views/login.html',{version:config.version});
//res.json('done')
});
HTML Code
<label style="font-size:10px;float: right;"><%= version %></label>
Current Result:-
Nothing is coming
Expected Result:-
<label style="font-size:10px;float: right;">3.9</label>
I have set this version number in my config which I have imported in my login.js, but still, I am not getting the output. Does anyone have any idea about it?
If you don't want to use a templating engine like ejs or pug then you can just send a get request with axios or fetch to your node server and send a response.
Here's a sample on how you can do it. Change it according to your needs.
index.html
<!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>Document</title>
</head>
<body>
<h1 id="title">My page</h1>
<script>
fetch('http://localhost:5000/version').then(function(response) {
return response.json();
}).then(function(myJson) {
document.getElementById('title').innerHTML = myJson;
});
</script>
</body>
</html>
server.js
const express = require('express');
const app = express();
const PORT = 5000;
app.get('/', (req, res) => {
res.sendFile('index.html', {root: __dirname });
});
app.get('/version', (req, res) => {
const myVersion = 'My version is 0.5';
res.json(myVersion);
});
app.listen(PORT, () => {
console.log(`Server running on PORT ${PORT}`);
});
I could not find the external js/css files using Angular.js and Node.js. I am explaining my code below.
Node/app.js:
require('./config/config');
require('./models/db');
require('./config/passportConfig');
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const rtsIndex = require('./routes/index.router');
var app = express();
var morgan = require('morgan');
var methodOverride = require('method-override');
var appRoot = require('app-root-path');
var path=require('path');
var reqPath = path.join(__dirname, '../');
console.log('app',reqPath + 'angularjs/dist');
//var corsOptions = {"origin": "http://localhost:4202", "methods": "GET,PUT,DELETE,POST", "preflightContinue": false, "optionsSuccessStatus": "204"};
//app.use(cors(corsOptions));
// middleware app.use( bodyParser.urlencoded({ extended: true }) );
app.use(bodyParser.json());
app.use(cors());
app.use(passport.initialize());
app.use('/api', rtsIndex);
app.use(express.static(reqPath + 'angularjs/dist/')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' })) // parse application/x-www-form-urlencoded
app.use(methodOverride()); // simulate DELETE and PUT
app.get('/',function(req,res){
res.sendFile(reqPath+'angularjs/index.html');
});
// error handler
app.use((err, req, res, next) => {
if (err.name === 'ValidationError') {
var valErrors = [];
Object.keys(err.errors).forEach(key => valErrors.push(err.errors[key].message));
res.status(422).send(valErrors)
}
else{
console.log(err);
}
});
// start server
app.listen(process.env.PORT, () => console.log(`Server started at port : ${process.env.PORT}`));
The above is my server side code and my client side code is given below.
angularjs/index.html:
<!DOCTYPE html>
<html lang="en" ng-app="lendingkart">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to Lendingkart</title>
<link rel="icon" href="dist/images/favicon.png" />
<!--Plugin CSS-->
<link href="dist/css/plugins.min.css" rel="stylesheet">
<!--main Css-->
<link href="dist/css/main.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<script src="dist/js/angularjslatest.js" type="text/javascript"></script>
<script src="dist/js/angularuirouterlatest.js" type="text/javascript"></script>
<script src="dist/js/route.js" type="text/javascript"></script>
<script src="dist/js/angularcaps.js" type="text/javascript"></script>
<script src="dist/js/angular-messages.js" type="text/javascript"></script>
<script src="dist/js/angularuibootstrap.js" type="text/javascript"></script>
<script src="dist/js/ng-file-upload-shim.min.js"></script>
<script src="dist/js/ng-file-upload.min.js"></script>
<script src="dist/js/dirPagination.js"></script>
<script src="dist/js/angular-chosen.min.js"></script>
</head>
<body>
<div ui-view>
</div>
<!-- jQuery -->
<script src="dist/js/plugins.min.js"></script>
<script src="dist/js/common.js"></script>
<script src="dist/js/jquery.mousewheel.min.js" charset="utf-8"></script>
<script src="dist/js/raphael.min.js" charset="utf-8"></script>
<script src="dist/js/jquery.mapael.js" charset="utf-8"></script>
<script src="dist/js/india.js" charset="utf-8"></script>
</body>
</html>
Here I am using the UI-ROUTER for get the pages.
angularjs/dist/route.js:
var Admin=angular.module('lendingkart',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination','angular.chosen']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider,$locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'views/login.html',
controller: 'loginController'
})
})
Here my issue is when index page is loading it could not get the external files and getting this GET http://localhost:3003/dist/css/plugins.min.css net::ERR_ABORTED error. As i am using two diferent folder for node.js and angular.js then I am getting these issues. I need to resolve those issues and access the required pages.