简体   繁体   English

node.js 不加载 javascript 文件

[英]node.js does not load javascript file

I am a total newbie to node.js.我是 node.js 的新手。

My problem is that the html-file 'index.html' called as 'localhost:5000' seems not to load the javascript file 'test.js'.我的问题是名为 'localhost:5000' 的 html 文件 'index.html' 似乎没有加载 javascript 文件 'test.js'。

I start the server by我启动服务器

nodejs server.js nodejs server.js

from a shell.来自 shell。 The files are这些文件是

server.js: server.js:

var http = require('http');
const process = require('process'); 
var fs = require('fs');

var server = http.createServer(function (request, response) {

    if (request.url === "/") {
        fs.readFile("index.html", function (error, pgResp) {
            if (error) {
                response.writeHead(404);
                response.write('Page is not found');
            } else {
                response.writeHead(200, { 'Content-Type': 'text/html' });
                response.write(pgResp);
            }

            response.end();
        });
    } else {
        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write('<h1>Default Content</h1>');
        response.end();
    }});
server.listen(5000);
console.log('Server is listening on 5000');
console.log(process.cwd())

The path process.cwd() is the path of the three files server.js, index.html and test.js路径 process.cwd() 是 server.js、index.html 和 test.js 三个文件的路径

index.html:索引.html:

<html>
<body>
    <center>
    <h2>Testing NodeJS Application </h2>
    <p> This is my first web application using NodeJS </p>
    </center>
    <script  type="text/javascript"  src="test.js"></script>
    <script>
      alert('Even this is a Test!');
    </script>
</body>
</html>

and test.js:和 test.js:

alert('I am here!');

The alert in index.html is shown, the alert in test.js is not. index.html 中的警报显示,test.js 中的警报没有。

I am using ubuntu 18.04.我正在使用 ubuntu 18.04。

Thanks in advance提前致谢

Peter彼得

The issue is the way you are importing the test.js script in your HTML file:问题是您在 HTML 文件中导入test.js脚本的方式:

    <script  type="text/javascript"  src="test.js"></script>

This file is being loaded on your browser, but the route provided in src= can't be resolved since "test.js" is not a valid URL or route to the file where you can load it from.此文件正在您的浏览器上加载,但无法解析src=中提供的路径,因为"test.js"不是有效的 URL 或指向您可以从中加载它的文件的路径。

You should first define where are you going to expose your "test.js" file from, so it can be fetched from your browser, and then, correct the value in src= to the actual URL.您应该首先定义要从哪里公开"test.js"文件,以便可以从浏览器中获取它,然后将src=中的值更正为实际的 URL。

For example, a common practice is exposing public files in a /public/ folder in your server code, then expose the files in there when the URL matches such /public/**some-file.js pattern.例如,一种常见的做法是在服务器代码的/public/文件夹中公开公共文件,然后在 URL 匹配此类/public/**some-file.js模式时公开其中的文件。

In your code you can achieve that by doing:在您的代码中,您可以通过以下方式实现:

//...
var path = require('path');

var server = http.createServer(function (request, response) {

    if (request.url.startsWith("/public/")) {
        fs.readFile(path.join(__dirname, path.normalize(req.url)), function (err,data) {
          if (err) {
            res.writeHead(404);
            res.end(JSON.stringify(err));            
            return;
          }
        res.writeHead(200);
        res.end(data);
      });

      return;
    }

    if (request.url === "/") {
       // ...      
    } else {
       // ...
    }});

//... rest of your code

You can find more details in this guide: How to serve static files .您可以在本指南中找到更多详细信息: 如何提供 static 文件

This is the final code I use.这是我使用的最终代码。 I placed the javascript file test.js in a folder named public.我将 javascript 文件 test.js 放在名为 public 的文件夹中。

var path = require('path');
var http = require('http');
var static = require('node-static');
const process = require('process'); 
var fs = require('fs');


var server = http.createServer(function (request, response) {

    if (request.url.startsWith("/public/")) {
        fs.readFile(path.join(__dirname, path.normalize(request.url)), function (err,data) {
          if (err) {
            response.writeHead(404);
            response.end(JSON.stringify(err));            
            return;
          }
        response.writeHead(200);
        response.end(data);
      });

      return;
    }

    if (request.url === "/") {
        fs.readFile("index.html", function (error, pgResp) {
            if (error) {
                response.writeHead(404);
                response.write('Page is not found');
            } else {
                response.writeHead(200, { 'Content-Type': 'text/html' });
                response.write(pgResp);
            }

            response.end();
        });
    } else {

        response.writeHead(200, { 'Content-Type': 'text/html' });
        response.write('<h1>Default Content</h1>');
        response.end();
    }
});

server.listen(5000);

console.log('Server is listening on 5000');
console.log(process.cwd())

Many thanks!!!!非常感谢!!!!

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

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