简体   繁体   中英

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

So, I've got a web application with 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 app.js code:

const express = require('express');
const Datastore = require('nedb');

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

const db = new Datastore('db.db');
db.loadDatabase();

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

My folder structure:

app.js
db.db
  ~~public~~
    index.html
    ~~assets~~
      ~~js~~
        index.js
      ~~css~~
        index.css
        normalize.css

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.

app.listen 应该在文件的末尾

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM