Really sorry for this stupid simple question, but I have tried to get this working for 20+ hours and I'm exhausted... Also searched/tried probably a 100+ ways to execute this.
I have a node server called server.js , html page called index.html and a javascript file called main.js .
I am trying to simply load the index.html-file on request (when loading http://localhost:2500/ ) and it works, but I just can't get the damn main.js to load ... so it only prints what ever is on the index.html-file.
server.js-file:
var http=require('http');
var fs=require('fs');
var express=require('express');
var app=express();
// var path=require('path');
// app.use("/", express.static(__dirname));
// app.use(express.static(path.join(__dirname+"/public")));
app.use(express.static('public'));
//404 response
function send404response(response) {
response.writeHead(404,{"Context-Type":"text/plain"});
response.write("error 404:page not found");
response.end();
}
//Handle user request
function onRequest(request,response) {
if(request.method=='GET' && request.url =='/'){
response.writeHead(200,{"Context-Type":"text/html"});
fs.createReadStream("public/pages/index.html").pipe(response);
}
else {
send404response(response);
}
}
http.createServer(onRequest).listen(2500);
console.log('server is running');
index.html-file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- <link rel="stylesheet" type="text/css" media="screen"
href="main.css" /> -->
</head>
<body>ddfg
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
main.js doesn't really contain anything worth linking. It works well without node being involved.
edit: Forgot to include file structure.
server.js is on the root
public/js/main.js
public/pages/index.html
To import javascript files in node you can do it by something like:
const myJsFunctions = require('./main.js');
then you can call your functions by something like myJsFunctions.functionName()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.