html不能调用file.js

我创build了我的第一个server.js,index.html和test.js. 当我运行节点时,索引页面不能调用test.js

var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res) { fs.readFile('./index.html', 'utf-8', function(error, content) { res.writeHead(200, {"Content-Type": "text/html"}); res.end(content); }); }); server.listen(8080); 

的index.html

  <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>PLAN</title> <script type="text/javascript" scr="test.js"></script> </head> <body> hello </body> </html> 

test.js

 "use strict"; alert("aa1"); 

有你的两个问题。

  1. 不正确的<script>标记属性,在index.html文件中从scr更改为src

  2. 您的服务器需要提供JavaScript文件,即fs.readFile('./test.js') ,所以请将您的server.js更改为以下内容。

 var http = require('http'); var fs = require('fs'); var path = require('path'); http.createServer(function (request, response) { var filePath = '.' + request.url; if (filePath == './') filePath = './index.html'; var extname = path.extname(filePath); var contentType = 'text/html' if (extname == '.js') contentType = 'text/javascript'; fs.readFile(filePath, function(error, content) { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); }); }).listen(8080); console.log('Server running at http://127.0.0.1:8080/'); 

我认为这应该工作。