If you are using http for a NodeJS application, you may have run into an issue where none of your images are loading on a site. Instead you are greeted with nice little “no image” logos.
The issue is that our NodeJS server has not been instructed to load anything other than index.html. So other things like images, or even CSS from our style.css file wont work properly.
To fix the issue, we need to to tell NodeJS what to do when other files are requested. As a side note, the person browsing the site may not be requesting the resources directly, but index.html file requests the css file or images hence creating a new web request.
Let’s say we are starting with the following code as a starting point.
var http = require('http')
var fs = require('fs')
var path = require('path')
var url = require('url')
http
.createServer(function (req, res) {
let pathname = url.parse(req.url).pathname
if (
req.method === 'GET' &&
(pathname === '/' || pathname === '/index.html')
) {
res.setHeader('Content-Type', 'text/html')
fs.createReadStream('./index.html').pipe(res)
return
}
return res.end()
})
.listen(3000)