使用Node,我无法从应用程序文件中加载静态HTML页面

时间:2018-06-20 22:23:20

标签: html node.js express

我正在尝试加载HTML页面,以向应用程序发出请求。如果将HTML放入服务器定义的res.end('')函数中,则HTML可以很好地加载,但这很脏。在下面的代码中,我想加载index.html作为根路由。我不知道自己在做什么错,我尝试使用重定向而不是sendFile也不起作用。

const pg = require('pg');
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
const  $ = require('jquery');
const path =  require('path')

const connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/hiking';

const server = http.createServer((req,res) => {});

var app = express()

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
app.use(express.static(__dirname));

app.get('/', function(req, res, next) {
    res.sendFile(path.join(__dirname + '/index.html'));
});



app.post('/inputs', function(req,res){
    var firstName = req.body.firstName;
    var lastName = req.body.lastName;
    var mountainName = req.body.mountainName;
    console.log(req.body);
});




const client = new pg.Client(connectionString);
client.connect();
const query = client.query('SELECT * from public.hike LIMIT 1', (err, res) => {
    if (err){
        console.log(err.stack)
    } else
        console.log(res.rows)
}) ;

console.log("Ready.");

server.listen(3000);

1 个答案:

答案 0 :(得分:0)

这是一个包含您感兴趣的代码的存储库:https://github.com/blakedietz/so-express-static-index

const express = require('express')
const app = express()

app.use('/', express.static('public'))

app.listen(3000, () => console.log('Example app listening on port 3000!'))