I am having a big problem with linking JavaScript files into HTML files.
My HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Express App</title>
</head>
<body>
<h1>GET Requests</h1><br/>
<input type="number" name="id" id="id-input>
<button type="submit" onclick="findPerson()">Submit</button>
<script src="./index.js" type="text/javascript"></script>
</body>
</html>
This code looks just fine, in fact, here is my JavaScript code:
const express = require('express');
const app = express();
const server = 'http://localhost:3000';
app.connect(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + "/" + "index.html");
});
const findPerson = () => {
var ID = window.document.getElementById('id-
input').value;
console.log(ID);
};
app.listen(8080, () => {
console.log('App is listening on port 8080');
});
Now, for some reason, when I inspect the page and go to the console, it says this:
Refused to execute script from
'http://localhost:8080/index.js' because
its MIME type ('text/html') is not executable, and
strict MIME type checking is enabled.
And also this:
Failed to load resource: the server responded with
a status of 404 (Not Found) index.js:1
I can see two errors with your code:
The 404 error means that your not linking to the right path, please check where is your index.js relative to your index.html
Even if it will load it, your code can not be executed because it's a server side code.
When you're including scripts in your browser it should be only client side code
Related
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.
I have a very simple https Nodejs server that serves an index.html that includes a request for a Javascript file. I cannot seem to get the browser to recognize the Javascript file.
<html>
<head>
<script src="deviceMotion.js"></script>
</head>
<body>
</body>
</html>
For this example, the contents of deviceMotion.js are immaterial. When I load the page and check Crhome debug tools, I receive a syntax error in the first line of the Javascript file, saying
Uncaught SyntaxError: Unexpected token '<'
I look at the "javascript" file's contents only to see that it is exactly the same as my index.html. This leads me to believe that there is an issue with the way my Node HTTPS server is serving the Javascript. Likely, it is just serving the html twice, even though my console logs show 3 separate requests being made, and only 2 when I remove the script tag from index.html. Obviously, it is trying to request the Javascript file, but there is something not right.
Here is the code for my server app.js
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
console.log("request received");
console.log(req.headers.referer);
fs.readFile('./src/index.html', function (error, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
My files are structured such that I have app.js in the same directory as a folder called "src" and I have index.html and deviceMotion.js under src.
How can I control what files I serve and when depending on incoming requests? How can I differentiate requests made in order to serve the right file? I have tried parsing req.baseUrl and req.path and both are undefined.
Your Node.js server always returns a HTML file and sets the content type to HTML, so when your website requests the JavaScript file, it returns a HTML file, causing the Uncaught SyntaxError: Unexpected token '<' error. To fix the error, don't set the content type and let the browser figure it out, and also modify the code to return the requested file.
I have written some possible code below. However, it will need to be modified to suit your file structure.
const server = http.createServer((req, res) => {
console.log("request received");
console.log(req.headers.referer);
fs.readFile('./' + req.url, function (error, data) {
res.end(data);
});
});
I'm trying to write simplest possible server that serves html page with client side scripts.
Already tried based on http://expressjs.com/en/starter/static-files.html,
Using express.js to serve html file along with scripts, css, and images and
How to load JS file in html using express server, but still I don't get it.
File structure I'm using:
node_modules
resources
resources/page.html
resources/script.js
index.js
package.json
index.js:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(__dirname + '/resources'));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname , 'resources', 'page.html'));
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
page.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
Content
</body>
<script scr="script.js"></script>
</html>
script.js:
var i = 0;
setInterval(() => {
if (i < 10) {
console.log(i);
i++;
}
}, 100);
I type in google chrome browser address localhost:3000/ and page is successfully loader ("Content" string is displayed), but script script.js is not running (empty console). I expect browser to retrieve script.js file and print numbers to console when page.html is loaded.
In the page.html file, change the property scr to src in the script tag and it will work.
Apologies for the confusing title, the confusing title is a byproduct of my own confusion.
I am working with Node.js to write a web server and an api. Everything was going well, until I ran into this problem. Here is my server/api code:
const express = require('express');
const app = express();
const port = 9001;
const bodyParser = require('body-parser');
const mysql = require('mysql');
app.get('/profile/:url', (request, response) =>{
app.use('/profile/:url', express.static(__dirname+'/static_pages'));
response.sendFile('static_pages/test.html', {root: __dirname});
});
Here is test.html:
<!DOCTYPE html>
<html lang= "en">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript" src="./test.js"></script>
</head>
<body>
<div class="test">test</div>
</body>
</html>
here is test.js:
console.log('i run correctly!');
Now test.html does everything as expected if I open the file with a browser. However, if I run the server and navigate to 127.0.0.1:9001/profile/XXXXX , I get the following error:
Uncaught SyntaxError: Unexpected token <
Confused, I checked under "Sources" in Chrome devtools, and despite Chrome saying that it's loading "test.js" the code that it's running as "test.js" is identical to that of "test.html". Does anyone know why this is happening?
I used an identical method in order to deliver html/css/js in my other rest calls in the same file, and all of those pages are working as intended.
app.get('/profile/:url', (request, response) =>{
app.use('/profile/:url', express.static(__dirname+'/static_pages'));
response.sendFile('static_pages/test.html', {root: __dirname});
});
That doesn't make sense.
Every time you get a request for /profile/:url you try to set up the static plugin, then you return the contents of test.html.
When the browser asks for /profile/test.js that code … returns the contents of test.html.
Presumably you are planning to put some dynamic code in there to generate the profile page dynamically. That means you should not put the JS under `/profile/ because it isn't a profile page.
So:
Configure the static plugin properly:
app.get('/profile/:url', (request, response) =>{
response.sendFile('static_pages/test.html', {root: __dirname});
});
app.use(express.static(__dirname+'/static_pages'));
Point the URL at the right place:
<script src="/test.js"></script>
Note the . is removed so you are accessing from the root instead of from the current path segment.
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.