Node.js服务器给脚本和图像带来了问题

我刚开始使用node js,并且移动了我的一个网站:

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

index.html是我的网站主页。 只有html的作品,但如果我把标签(例如包括jquery),它给萤火虫JS错误:未捕获的语法错误:意外的标记<在jquery.js,然后当然'$是不确定的'。 它也不加载图像。

我不需要做一些路由或使用Express框架或任何东西,它只是一个简单的单页网站。 我究竟做错了什么 ?

您的服务器不处理图像或其他资源的请求。 所有请求都被赋予./index.html页面的相同响应。

这意味着,如果页面中包含外部脚本或图像,当浏览器为这些资源发出请求时,原来的index.html页面将被交付。

NodeJS是相当低级的。 您需要将服务器设置为根据每个请求的URL手动处理对不同types资源的请求。

你最好的select是阅读一些NodeJS教程。 他们应该涵盖提供内容的基础知识,尽pipe其中许多不会涉及到底层的细节,并会build议像Connect或Express这样的软件包。

改变你的代码,你会看到所有的资源被请求。

 var http = require('http'); var fs = require('fs'); var url = require('url'); var path = require('path'); var app = http.createServer(function (req, res) { var pathname = url.parse(req.url).pathname; var ext = path.extname(pathname).toLowerCase(); console.log(pathname); if (ext === ".html") { fs.readFile('./index.html', 'utf-8', function(error, content) { res.writeHead(200, {'Content-Type' : 'text/html'}); res.end(content); }); } }); app.listen(8080);