This question already has answers here:
How to load javascript code to an html file at runtime?
(5 answers)
Closed 10 days ago.
My webpage creates a new script element and then loads the script from a localhost server. The problem is that the script cannot be loaded and shows PROTOCOL ERROR:
https://localhost:4200/script/test.js net::ERR_SSL_PROTOCOL_ERROR
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link href="./public/nps.style.css" rel="stylesheet" />
<script>
j = document.getElementsByTagName('script')[0],
k = document.createElement('script');
k.src = 'http://localhost:4200/script/test.js';
j.parentNode.insertBefore(k,j);
</script>
</head>
<body>
<p>Testing</p>
</body>
</html>
Then create a localhost server to listen it so the JavaScript file can be downloaded
index.js:
const express = require('express');
const cors = require('cors');
const { test } = require('./script/test.js');
const api = express();
api.use(cors({origin: '*'}));
api.use('/script', express.static('public'));
api.listen(4200, () => {
console.log("Server listening");
})
test.js:
alert("it works!");
How can I solve this issue?
Update:
Initially I had the source of the new script element as 'https://localhost:4200/script/test.js', So I changed to http, a new error occurred:
GET http://localhost:4200/script/test.js net::ERR_ABORTED 404 (Not Found)
Have you considered not using https? It looks like this could be your issue running locally.
The protocol error is the giveaway.
You just change 2 lines of your index.js code to solve it. Try with this code :
const express = require('express');
const cors = require('cors');
// const { test } = require('./script/test.js');
const api = express();
api.use(cors({ origin: '*' }));
api.use(express.static('public'));
api.use('/script', express.static('script'));
api.listen(4200, () => {
console.log("Server listening");
});
And make sure your directory/file management looks like this :
Related
I want to develop a very basic blog app with express.js and I was trying to create a webpage where I could write a post from the browser and store it into a db after submitting it.
By searching on the internet I came upon the ckeditor package, which would allow me to format my blog post before submitting it to the database. I read the documentation and tried to integrate the package in the html code together with the javascript scripts necessary to load the software.
However, when I load the new_post page in my browser I see that the browser is not loading correctly the ckeditor even though I am serving the javascript script necessary to run it as a static resource through the express.static method.
Here you can find the necessary info to check my issue:
Project Structure:
project structure
app.js
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
const PORT = 5000;
const newPostRouter = require(".\\routes\\new_post.js");
app.set("view engine", "ejs");
app.use("/public", express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: false }));
//Homepage
app.get("/", (req, res) => {
res.render("homepage", { title: "My Express App", message: "Hello World!" });
});
//Write a new post
app.use("/new-post", newPostRouter);
//Listener
app.listen(5000, () => {
console.log(`Server listening on port ${PORT}...`);
});
routes/new_post.js
const express = require("express");
const router = express.Router();
const path = require("path");
router.get("/", (req, res) => {
res.render("new_post");
});
router.post("/", (req, res) => {
const title = req.body.title;
const content = req.body.content;
res.redirect("/");
});
module.exports = router;
views\new_post.ejs
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>
</head>
<body>
<img src="..\public\dog-img.jpg" alt="derp" />
<h1>Classic editor</h1>
<div id="editor">
<p>This is some sample content.</p>
</div>
<script
src="..\public\js_scripts\new_post.js"
type="application\javascript"
></script>
</body>
</html>
public\js_scripts\new_post.js
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
As you can see I am trying to send the static resources to the client browser by using the express.static method in the app.js file. However when I try to load the page in the browser, this is the result I get:
result 1
The dog-img.jpg, also contained in the public folder, is correctly sent to the client yet the javascript file new_post.js is not.
I've also tried to modify the ejs file by substituting the script tag with
<script>
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
</script>
When I do this the editor correctly loads in my browser:
result 2
Since I am trying to follow the best practices I'd like to keep my js files separated from the html/ejs files and therefore I'd like to call the scripts from an external source and not internally.
Can anybody help me understand what is wrong with my code?
In app.js you need to write
app.use(express.static(path.join(__dirname, 'public')));
code to access all data inside the asset folder.
then you need to simple add or load this inside your .ejs file.
<img src="/images/img1.jpg" alt="" srcset="">
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/javascripts/index.js'></script>
For More Details Please visit this link Serving static files in Express
This question already has answers here:
How can I download a file using window.fetch?
(10 answers)
Closed 9 months ago.
I am working in a fullstack project I have backend folder using nodejs with server.js file of the following code
const express = require("express");
const cors = require("cors");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "puplic/uploads")));
app.use(cors());
app.get("/", async (req, res) => {
res.download("b.rar");
});
app.listen(3000, () => {
console.log("server connected");
console.log(path.join(__dirname, "puplic/uploads"));
});
and client side of index.html of the following code
<!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>Document</title>
</head>
<body>
<button id="btn">press</button>
<script src="index.js">
</script>
</body>
</html>
and client side index.js of the following code
let btn=document.getElementById("btn")
btn.onclick=()=>{
fetch("http://localhost:3000/",{
method:"GET",
mode:"cors"
}).then(res=>
{
}
)
}
how i can fetch the server side and download the file in the client pc
when the client press the button
I would recomment to redirect to a blank page and set a download header there.
Client side would look like this:
let btn=document.getElementById("btn")
btn.onclick=()=>{
window.open("http://localhost:3000/", '_blank')
}
on the serverside you have to set a download header, code would look like this:
app.get("/", async (req, res) => {
res.download("b.rar");
});
optional you can set the headers by yourself using:
app.get("/", async(req, res) =>.{
res.set({
"Content-Disposition": "attachment; filename=\"b.rar\"",
"Content-Type": "application/x-rar-compressed, application/octet-stream"
});
const fs = require('fs/promise');
fs.readfile('./b.rar').then(file => {
res.send(file);
})
});
I havent tested this whole stuff but maybe it can help you. Optional it is enough to use an tag instead of a button and manage the redirection there since some browsers deny window.open from javascript due to cross site injection.
I create a server using nodejs with express
server.js
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
router.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
//__dirname : It will resolve to your project folder.
});
//----------------------------------------------------------------------
//add the router
app.use(express.static(__dirname + '/View'));
//Store all HTML files in view folder.
app.use(express.static(__dirname + '/Script'));
//Store all JS and CSS in Scripts folder.
app.use('/', router);
app.listen(process.env.port || 3000);
And use html with javascript.
index.html
<html>
<head>
<meta charset="utf-8"/>
</head>
<link rel="stylesheet" href="./index.css">
<script type="text" src="./server.js"></script>
<script src="./index.js"></script>
<body>
<h1>Automatico</h1>
<button onclick="autohabilitar();">Habilitar</button>
<button onclick="autodeshabilitar();">deshabilitar</button>
<br>
<h1>Foco-1</h1>
<button onclick="f1habilitar();" id="f1h">Habilitar</button>
<button onclick="f1deshabilitar();"id="f1d">deshabilitar</button>
</body>
</html>
index.js
document.getElementById("f1h").disabled=true;
document.getElementById("f1d").disabled=true;
}
function autodeshabilitar(){
document.getElementById("f1h").disabled=false;
document.getElementById("f1d").disabled=false;
}
function f1habilitar(){
document.getElementById("f1h").disabled=true;
document.getElementById("f1d").disabled=false;
}
function f1deshabilitar(){
document.getElementById("f1d").disabled=true;
document.getElementById("f1h").disabled=false;
}
I need the function
function apagarf1(){
led1.off();
}
located in server.js for use in onclick of the button...
I tried export the function, import the script in the html, use johnny-five in another script...
I’m not super familiar with Johnny 5. But I do know you can’t access node.js specific stuff from the browser.
Your best bet will be to set up a basic api endpoint in express that you call from your front end code. When that endpoint gets hit you can trigger your nodejs function to turn the led off.
In your server file add this:
app.get('/led-off', (req, res) => {
apagarf1()
return res.send('LED off');
});
On your front end make a fetch() call to that endpoint and that should work.
I am running node project with html and javascript. How can I display the alert box in html.
My html (index.html)
<!DOCTYPE html>
<html>
<head>
<script src="./watch.js"></script>
</head>
<body onload="showBox()">
<h1>Heading</h1>
<p>Paragraph</p>
</body>
</html>
watch.js
function showBox(){
alert("this is alert box");
}
server.js
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
});
Error
I think that the problem is that you are not telling nodeJS where your statics files are.
For me, the simplest way is to set the server with Express
$ npm install express
And then setting up the server and where your static directory is:
var express = require('express');
var app = express();
//setting middleware
app.use(express.static(__dirname + 'public')); //Serves resources from public folder
var server = app.listen(5000);
There are other ways to doit using Native NodeJS, here are some resources:
Nodejs.org - How to serve static files
Also, you can write the script directly in your html file:
<!DOCTYPE html>
<html>
<head>
<script>
function showBox(){
alert("this is alert box");
}
</script>
</head>
<body onload="showBox()">
<h1>Heading</h1>
<p>Paragraph</p>
</body>
</html>
Your server is only ever returning index.html, no matter what path is requested. So, your watch.js is never loaded. The contents of index.html are returned instead of watch.js.
Either handle the other paths in your server code, or use something like Express.static, which does this for you.
Your http server is only outputting the index.html file. You need to either put all your client-side code in that file, or edit your server to load the watch.js file and make it able to send either page.
The first is simpler. Here's a basic example for the second. Most browsers will assume the mime-type by the extention.
Also, change your html for the script name from "./watch.js" to just "watch.js".
I simplified this down to be easier to understand... also const is deprecated and wont work on newer versions of node.
Specifying the mime header like you did is more compatible (Chrome and Firefox will assumebased on file extension, but for example Opera does not, or didnt used to).
var http = require('http');
var fs = require('fs');
var doc = {}
doc['/index.html'] = fs.readFileSync('index.html');
doc['/watch.js'] = fs.readFileSync('watch.js');
var server = (request, response)=>{
response.end(doc[req.url]);
}
http.createServer(server).listen(8080);
So I am trying to write a simple node server that will fetch a very simple html file when it is hit with a get request at the root directory. Everything works fine until I try to attach a javascript file to my html file, then I get hit with the error Uncaught SyntaxError: Unexpected token < I have realized that this is just a 404 error, but I am completely unable to figure out how to make this stop happening.
test.html
<!DOCTYPE html>
<html>
<head>
<title>title</title>
</head>
<body>
<script type = "text/javascript" src = "/home/danny/Documents/Application/server/test.js"> </script>
booya
</body>
</html>
app.js
/**
* Main application file
*/
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var tweet = require('../models/tweet.js');
// Connect to database
mongoose.connect('mongodb://localhost/test');
// Setup server
var express = require('express');
var app = express();
require('./config/express');
require('./routes')(app);
app.engine('html', require('ejs').renderFile);
var server = require('http').createServer(app);
// Start server
server.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
console.log(__filename);
// Expose app
exports = module.exports = app;
routes.js
/**
* Main application routes
*/
'use strict';
module.exports = function(app) {
// Insert routes below
app.route('/aa')
.get(function(req, res) {
res.sendFile('/home/danny/Documents/Application/server/test.js')
})
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
// res.set('Content-Type', 'text/html');
res.render('/home/danny/Documents/Application/src/test.html');
});
};
Anybody have any ideas why it is unable to find the file?
I am going to take a long guess here, but maybe it's because you're doing this: /home/danny/Documents/<xyz>...?
This won't work because you're attempting to link to http://yourdomain.com/home/danny/Documents/<xyz>.
Try fixing this by putting a path that the web server will understand.