@neva29101 (NEVA)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ルーティングが上手くいきません。ルーティングでHTMLファイルを表示させたいです。

-------------------------server.jsの記述---------------------------------
const express = require('express');
const app = express();
const PORT = 2502;

// router
const shopRouter = require('./routes/shop');

app.use(express.static('public'));

// send homepage
app.get('/', (req, res) => {
res.sendFile(__dirname + ('/public/html/top/top.html'))
});

// routing
app.use('/shop', shopRouter);

// log
app.listen(PORT, () => {
console.log("START SERVER");
});

------------------------routes/shop.jsの記述-------------------------------
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => {
res.sendFile(__dirname + '/public/html/shop/home.html')
});

router.get('/yakisoba', (req, res) => {
res.sendFile(__dirname + '/public/html/shop/yakisoba.html')
});

module.exports = router;

0 likes

2Answer

この行:
__dirname + '/public/html/shop/home.html'

は、実際には以下のパスを探しています
routes/public/html/shop/home.html

つまり、__dirname が routes フォルダ内である場合、その中の public/html/shop/home.html を参照することになります。

もし HTML ファイルが routes フォルダの外側にある public フォルダ内に存在する場合は、以下のように path.join() を使って正しいパスを指定する必要があります:

------------------------routes/shop.jsの記述-------------------------------
const express = require('express');
const router = express.Router();
const path = require('path');

router.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/html/shop/home.html'));
});

このようにすることで、../ を使って routes フォルダの外に出て、正しいファイルパスを指定できます。

1Like

Comments

  1. @neva29101

    Questioner

    回答ありがとうございました。表示することができました。

This answer has been deleted for violation of our Terms of Service.

Your answer might help someone💌