Skip to content
Advertisement

Node/Express: Database being printed on screen rather than index.html

So, I’m using Node, but all that’s printed on the screen is my database in JSON format and not index.html. This doesn’t occur when I use localhost, so I have no idea why it does show my index page. Can anyone help me?

My code:

const app = express();
app.listen(3000, () => console.log('listening'));

app.get('/api', (request, response) => {
    db.find({}, (err, data) => {
        response.json(data);
    });
});

Advertisement

Answer

I didn’t exactly understand your question properly but based on the code you will get a JSON response on localhost:3000/api and a blank screen on localhost:300 as you have not rendered or called for any views in your code.

You can use app.use(express.static(__dirname + '/public')) to access your directory and then use res.sendFile('index.html') to render index HTML file on any route you wish.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement