简体   繁体   English

node + html页面加载+ javascript,无法加载main.js文件

[英]node + html page load+ javascript, can't load main.js file

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.对于这个愚蠢的简单问题,真的很抱歉,但我已经尝试让它工作 20 多个小时,但我已经筋疲力尽了……还搜索/尝试了 100 多种执行此操作的方法。

I have a node server called server.js , html page called index.html and a javascript file called main.js .我有一个名为server.js的节点服务器、一个名为index.html 的html 页面和一个名为main.js的 javascript 文件。

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.我试图简单地根据请求加载 index.html 文件(加载http://localhost:2500/ 时)并且它可以工作,但我无法加载该死的 main.js ......所以它只是打印 index.html 文件中的内容。

server.js-file: server.js 文件:

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 index.html-文件

<!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. main.js 并不真正包含任何值得链接的东西。 It works well without node being involved.它在不涉及节点的情况下运行良好。

edit: Forgot to include file structure.编辑:忘记包含文件结构。

server.js is on the root server.js 在根上

public/js/main.js公共/js/main.js
public/pages/index.html公共/页面/index.html

To import javascript files in node you can do it by something like:要在节点中导入 javascript 文件,您可以通过以下方式进行:

const myJsFunctions = require('./main.js');

then you can call your functions by something like myJsFunctions.functionName()然后你可以通过myJsFunctions.functionName()类的东西调用你的函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM