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

时间:2018-10-08 10:49:08

标签: javascript html node.js

真的很抱歉这个愚蠢的简单问题,但是我试图使它工作20多个小时,但我已经筋疲力尽了……还搜索/尝试了100多种执行此方法的方法。

我有一个名为 server.js 的节点服务器,一个名为 index.html 的html页面以及一个名为 main.js 的javascript文件。 / p>

我正在尝试根据请求简单地加载index.html文件(加载http://localhost:2500/时),它可以工作,但是我只是无法加载该死的main.js > ...,因此它仅打印index.html文件中的内容。

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文件

<!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确实不包含任何值得链接的内容。它在不涉及节点的情况下运行良好。

编辑: 忘记包含文件结构。

server.js位于根目录上

public / js / main.js
public / pages / index.html

1 个答案:

答案 0 :(得分:0)

要在节点中导入javascript文件,您可以执行以下操作:

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

然后您可以通过类似myJsFunctions.functionName()

的方式调用函数