I have a folder with HTML files that have 2 different categories. One of them is the Main Page called arq.html which has the indexes of every other page. All of the other pages contain the actual information about a specific individual and have the name of arqx.html where x corresponds to the number of the page.
What I'm trying to do is to be able to click an index and go into the respective HTML page. Each of these indexes has the URL localhost:7777/arq/x.
For example localhost:7777/arq/7 should answer with the arq7.html file.
At the moment I have the following code:
var http = require('http')
var fs = require('fs')
http.createServer(function (req, res){
var num = req.url.split("/")[req.url.length-1]
fs.readFile('arq' + num +'.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'})
res.write(data)
res.end()
})
}).listen(7777);
console.log('Servidor à escuta na porta 7777...')
The var num
was something I saw to parse the URL so I could obtain the actual x. I'm not sure if it's the parsing that's wrong, or if I'm messing something up with the files locations.
Also, the error I'm getting:
_http_outgoing.js:696
throw new ERR_INVALID_ARG_TYPE('first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received undefined
at write_ (_http_outgoing.js:696:11)
at ServerResponse.write (_http_outgoing.js:661:15)
at ReadFileContext.callback (C:\Users\joao_\OneDrive\Ambiente de Trabalho\dataset\server1.js:8:13)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:273:13) {
code: 'ERR_INVALID_ARG_TYPE'
}
You should console.log(data)
to see what you are getting which isn't a string or a buffer.
You should also look at err
to find out if there was an error reading the file.
In this case, there is an error and thus data
is undefined
.
The error is caused by you getting the filename wrong.
req.url.split("/")[req.url.length-1]
req.url.split("/")
gives you an array, but that isn't what you are reading the .length
of. req.url
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.