skip to Main Content

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


  1. 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:

    const app = express();
    
    // Serve static files from a directory (e.g. 'public')
    app.use(express.static(path.join(__dirname, 'public')));
    
    // Define your routes
    app.get('/', (req, res) => {
        res.send('Some welcome text.');
    });
    
    // Example with 'funnyFile' and 'myProject'
    app.get('/funnyFile/Jokes.html', (req, res) => {
        res.sendFile(path.join(__dirname, 'public', 'funnyFile', 'Jokes.html'));
    });
    
    app.get('/myProjects/poj1/index.html', (req, res) => {
        res.sendFile(path.join(__dirname, 'public', 'myProjects', 'poj1', 'index.html'));
    });
    
    Login or Signup to reply.
  2. You should define routes for those files by using app.use and get request by router.get, then when you request that route you will access it.

       const express = require("express");
       //router object
        const router = express.Router();
        
        //routes GET | POST |UPDATE | DELETE ==>CRUD
        router.get(".path or url", call back function);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search