Cannot get a script file node js - javascript

I have a simple doubt but can't figure it out. I am starting node js app,from a localhost location and through the response i am sending a html file. But its node loading the script file which is inside the html.
Node js file
var express = require('express');
var app = express();
var ExpressPeerServer = require('peer').ExpressPeerServer;
app.get('/', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html'); });
var server = app.listen(9000);
var options = {
debug: true
}
app.use('/api', ExpressPeerServer(server, options));
server.on('connection', function(id) {
console.log("In Server connection")
});
server.on('disconnect', function(id) {
console.log("server Disconnected")
});
Html File
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdn.peerjs.com/0.3/peer.js"></script>
<script type = "text/javascript" src="script.js"></script>
</head>
<body>
<h1>ha ha this is Webrtc</h1>
</body>
</html>
script.js
function webRtcInit() {
alert("Inside Script")
}
$(document).on('ready', webRtcInit());
When i normally run the html file its loading the script file. But when i send the file through node js and load the script, I am getting the error , that it cannot get the script file, Why is this happening...?
Thanks

I am seeing few problems in your code:
this renders your html page, similarly, you need one for script.js.
app.get('/', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html');
});
either specific:
app.get('/script.js', function(req, res, next) {
console.log("before redirection");
res.sendfile('index.html');
});
or generic:
app.use(express.static('static')); // now place your static files in the static folder.
unrelated to the problem at hand, but, in script.js, it is webRtcInit not webRtcInit() :
$(document).on('ready', webRtcInit);

A node.js server does not serve any files by default (this is different that some other web servers). So, any file that you want it to serve must have a route for it or some type of middleware that handles it.
So, your code does have a route for /, but when the browser parses the index.html file that you return from that route and then tries to load script.js from your node.js server, you don't have a route for that and the server will return a 404 (not found).
The solution is to create a route for script.js. Since it's a static resource, you can probably use the express.static capability to serve all your static files. You can read about serving static files in express here.

Related

How to use javascript methd from external files in hbs file

Let's say i have a simple project, index.html and one .js file with a method:
<!DOCTYPE html>
<html lang="pl">
<HEAD>
<script src="controller.js"></script>
<meta charset="utf-8"/>
<title>Project</title>
</HEAD>
<body>
<textarea id ="someID" name = "textFieldName"></textarea>
<button onclick="showNewData()">Button</button>
<p id="score"></p>
</body>
</html>
function getText(){
value = document.getElementById('someID').value;
}
function showNewData(){
getText();
document.getElementById('score').innerHTML = "Current data: "+value;
}
I tried to do the same on localhost:3000. So i've done npm project with express and hbs dependencies. It start from server.js file:
const express = require('express');
const port = 3000;
const app = express();
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('index')
})
app.listen(port);
In "views" folder i have hbs file looked the same like former index.html file but it can't use javascript method from external file. Does anyone know how to do that?
in hbs file
As far as the browser knows, it is HTML. Clients do not care, and cannot know, if an HTTP response is generated by reading a static file or dynamically with some form of server side processing.
src="controller.js"
The value of the src attribute has to resolve to a URL containing the JavaScript
app.get('/', (req, res) => {
res.render('index')
})
The only URL your web server knows about (and so will provide anything other than a 404 error for) is /.
If you want /controller.js to provide a JS file then you need to write code to make that happen.
How to handle static files is covered in the Express Getting Started Guide.

Why am i getting a 404 js file, while including a script tag?

index.html
<head>
<script src="/main.js"></script>
</head>
Error:
GET http://localhost:3000/main.js
Structure
Project
app.js
view
index.html
main.js
I've tried src="main.js". /view/main.js
Very basic, but dont want to get stuck on this any longer... sigh.
if it helps my app.js file has this:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/view/home.html');
});
So, according to your comments - you are serving only the 'index.html' file instead of whole directory.
Try this code:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'view')));
//... other settings and server launching further
If you want to set serving static files to particular route - extend 'app.use' line with '/your-route', like this:
app.use('/your-route', express.static(path.join(__dirname, 'view')));
After that you can use <script src="main.js"></script> in your index.html

Send a index.html file when server is created

I want a file like index.html to be loaded when the server is created. When I execute the server.js using node, I send a response as text like this res.end("text"). But I want the index.html to load.
I tried to load it using sendFile() in app.get('/getFile') but when I type in the address bar, I get the text for all the urls..even for localhost:3000/getFile.
This is my server.js:
(function(){
var http = require("http");
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
// app.use(express.static(__dirname));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/views'));
var server = http.createServer(function(request, response) {
response.end("text");
});
server.listen('3000');
console.log("Server is listening");
app.get('/getFile',function(request,response){
// response.end('shi');
response.sendFile(path.join('/index.html'));
})
})();
Change the following in your code:
var server = http.createServer(function(request, response) {
response.end("text");
});
to this:
var server = http.createServer(app);
Now, you can serve your static index.html file with this code:
app.get('/', function(req, res, next){
// Serve the index.html file in the root directory of the website.
res.sendFile(path.join('/index.html'));
});
I hope this helps. If you have any questions, let me know.
EDITED
I just made a folder and wrote the following code and I have checked that this is working.
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/indexz.html');
});
app.listen(1339);
console.log('Open this link http://localhost:1337');
Steps
1 Copy the code given above in a new folder and name it whatever you want, name the file server.js
2 go to your cmd and propagate to location of your code and now npm install express
3 now type node server on console
4 open the link that is there on the console.
Note : Make sure there is folder name public and there is a file named
indexz.html in there.
Edited
Regarding proper client side files arrangement
You will have to keep all your files in public folder, first of all and attach them accordingly in your html document.
Example
<!-- Owl Carousel Assets -->
<link href="css/owl.carousel.css" rel="stylesheet">
<link href="css/owl.theme.css" rel="stylesheet">
<script src="js/jquery.min.js"></script>
<script src="angular.js"></script>
<script src="controller.js"></script>
and then within public folder you'll have folders named js and css and in root of the public folder your html files.
Looks your issue is with all the static assets.
In application server like express you have 3 different kind of elements to serve:
static content: this is all html, client side js, css, images and so on
server side templates or views, are documents you assemble with some sort of templating library like handlebars or jade to produce html
api that provide data in xml or more common json format
Your issue is how to serve a static part.
You should add to the static folder of your express app the folder where you build your angular app.
Not just the index.html you need the client side .js, .css and all images the page require.
UPDATE:
Here you could find the express documentation about static content.
UPDATE:
When you add a static folder to the express middleware, you should be able to access your file directly.
For example, if you have 2 files: $project/static/main.js and $project/static/js/my-lib.js, you should use the following urls:
http://127.0.0.1:3000/main.js
http://127.0.0.1:3000/js/my-lib.js
Considering you're executing the node http server on localhost on port 3000.
If you provide a specific path to access the static content, then you have to rewrite your url so.
If you use a line like:
app.use('/staticFolder', express.static('staticFolder'));
Than the urls to the mentioned files will be:
http://127.0.0.1:3000/staticFolder/main.js
http://127.0.0.1:3000/staticFolder/js/my-lib.js
Also pay attention to the path you provide to express.
You should give a proper path, and it's always safer to use absolute paths:
app.use(express.static(__dirname + 'staticFolder'));
or
app.use('/staticFolder', express.static(__dirname + 'staticFolder'));

Javascript file not loading in MEAN stack application

I am playing around and trying to learn the MEAN stack to create a single page application. I was able to get my back-end routes to work correctly. I've tested it using Postman and get the results I expect, however I cannot get my front-end to talk to the back-end correctly.
I reduced my front-end to very basic html and javascript, but still get a syntax error "Unexpected token <". When I inspect my coreTest.js file in the browser, I see that it's just a copy of my html file, rather than javascript code.
When I run index.html by itself (without server.js) coreTest.js runs just fine. I'm not sure why, when running my server.js file, my coreTest.js file doesn't work properly.
server.js
// Setup
var express = require('express');
var app = express(); // create app w/ express
var mongoose = require('mongoose'); // used for MongoDB connection
var morgan = require('morgan'); // log requests to the console
var bodyParser = require('body-parser'); // pull information from HTML POST
var methodOverride = require('method-override'); // simulate DELETE and PUT requests
// Configure
mongoose.connect('localhost:27017/test'); // connect to localhost db "test"
// varify connection
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
app.use(express.static(__dirname + '/public')); // set static files location
app.use(morgan('dev')); // log every request to console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-url
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse vnd.api+json as json
app.use(methodOverride());
// define db model
var Todo = mongoose.model('Todo', {
text: String
});
var router = express.Router();
router.route("/todos")
.get(function(req, res) {
Todo.find(function(err, todos) {
if (err)
res.send(err);
res.json(todos);
});
})
.post(function(req, res) {
var todo = new Todo();
todo.text = req.body.text;
todo.save(function(err) {
if (err)
res.send(err);
res.json({mes: "Todo item created"});
})
});
router.route("/todos/:todo_id")
.delete(function(req, res) {
Todo.remove( {
_id: req.params.todo_id
}, function(err, todo) {
if (err)
res.send(err);
res.json({mes: "Successfully deleted"});
});
});
// route to application
router.route("*")
.get(function(req, res) {
res.sendfile('./public/index.html');
});
// Register our routes
app.use('/api', router);
// Listen, start node app
app.listen(8080);
console.log("app listening on port 8080");
coreTest.js
alert("ping");
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Starter MEAN Single Page Application</title>
<script type="text/javascript" src="coreTest.js"></script>
</head>
<body>
I did it!! Wooo!!
</body>
</html>
I suspect the problem is between
app.use(express.static(__dirname + '/public'));
and
// route to application
router.route("*")
.get(function(req, res) {
res.sendfile('./public/index.html');
});
When you're running the server, your client-side code is trying to load "coreTest.js", which is matched by the last rule ; and so the server returns the content of index.html.
I'm not sure what you mean about "runing index.html by itself" ; if you mean "visiting file://..../public/index.html", it works because the browser will try to load coreTest.js from your file system.
Try using the "static" plugin only to serve files from "public", and use this prefix in the client side code :
app.use("/public", express.static(...))
and in the client
<script type=".." src="public/coreTest.js"></script>
Getting the path rights will depend on what's on your disk.
This might help, too : static files with express.js
I was able to solve my issue using what phtrivier recommended.
Instead of serving my files from "public" I chose to serve them from "api" because I already set my router to take requests from that path as well.
app.use("/api", express.static(__dirname + '/public'));
I didn't need to change my reference to coreTest.js in the html because my files were organized with coreTest already in the root directory like this:
public
-index.html
-coreTest.js

nodejs/express include local js file

Here is my current folder structure
css
app.css
js
app.js
node-modules
index.html
node-server.js
package.json
The node-server is hosting index.html, but I can't figure out how to get the app.js and app.css files to get loaded.
index.html loads them with:
<script src="js/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/app.css"/>
Here is the error message:
Failed to load resource: the server responded with a status of 404 (Not Found)
2http://localhost:3000/css/app.css Failed to load resource: the server
responded with a status of 404 (Not Found)
I know i need to require or load module or something, just can't figure out what.
Thanks
Reason
Node.Js does not server static content on it's own, routes has to defined for serving static content via Node.
Solution(Manual):
var express = require('express'),
path = require('path'),
app = express();
app.get('/index.html',function(req,res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/css/app.css',function(req,res){
res.sendFile(path.join(__dirname + '/css/app.css'));
});
app.get('/js/app.js',function(req,res){
res.sendFile(path.join(__dirname + '/js/app.js'));
});
app.get('/', function(req, res) {
res.redirect('index.html');
});
app.listen(8080);
Better Solution:
Directory Structure:
public
css
app.css
js
app.js
index.html
CODE:
var express = require('express'),
path = require('path'),
app = express();
// Express Middleware for serving static files
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res) {
res.redirect('index.html');
});
app.listen(8080);
As Tomasz Kasperek pointed out, you need to let Express know that you intend to host these files in a static directory. This is technically called defining static middleware.
This should look something like:
var express = require('express');
var app = express();
// first parameter is the mount point, second is the location in the file system
app.use("/public", express.static(__dirname + "/public"));
It's super simple and I suggest you go the route of making some sort of public folder, rather than bothering to make specific files and folders static.
Then the files would simply be referenced like so from the root index.html:
<link href="public/css/reset.css" rel="stylesheet" type="text/css">
Hope this helps you!
I got it to work by using this syntax
app.use(express.static('public'));
Copy the css and js files under the 'public' directory
and then add the reference in the index.html file
<link rel="stylesheet" href="/css/reset.css">
//we are in ./utils/dbHelper.js, here we have some helper functions
function connect() {
// connect do db...
}
function closeConnection() {
// close connection to DB...
}
//let's export this function to show them to the world outside
module.exports = {
connect(),
closeConnection()
};
// now we are in ./main.js and we want use helper functions from dbHelper.js
const DbHelper = require('./utils/dbHelper'); // import all file and name it DbHelper
DbHelper.connect(); // use function from './utils/dbHelper' using dot(.)
// or we can import only chosen function(s)
const {
connect,
closeConnection
} = require('./utils/dbHelper');
connect(); // use function from class without dot

Categories