I am working with Node.js servers. When I log on to the server, the code,
res.write("What ever text you choose")
will run and I will only get the "What ever text you choose" no matter what path I type. I know you can "write" a file so every time you log on to the server, it will give you that page. The problem I am having is that the server will only give me the one file. How can I request a different file based on the URL?
For example, When I type in localhost:9090, I’ll get the file I requested.
But if I type in localhost:9090/index.html or localhost:9090/funnyFile/Jokes.html or localhost:9090/myProjects/poj1/index.html, I’ll just get the same file, how can I access funnyFile and myProjects?
Here is my node server’s code.
const http = require('express')
const port = 9090
// Create a server object:
const server = http.createServer(function (req, res) {
// Write a response to the client
res.write("I choose this text");
// End the response
res.end()
})
// Set up our server so it will listen on the port
server.listen(port, function (error) {
// Checking any error occur while listening on port
if (error) {
console.log('Something went wrong', error);
}
// Else sent message of listening
else {
console.log('Server is listening on port' + port);
}
})
2
Answers
You imported
express
but you’re not using it.http
does not provide methods to serve static files/routing.Instead, use
express
to handle these, like so:You should define routes for those files by using
app.use
and get request byrouter.get
, then when you request that route you will access it.