无法获取/资源/卡

时间:2019-11-12 10:55:03

标签: node.js file express static serve

我在尝试通过expressJS提供静态文件时遇到问题。 我想使用虚拟路由从文件夹中提供文件。

我的应用程序架构如下

├── app
|   ├── assets
|       └── data
|           └── img
|               └── cards
|                   └── * (un bunch of image files)
|   └── index.js
|   └── server.js
├── node_modules
├── package.json
├── package-lock.json

我的index.js

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


//Serving images
app.use('resources/cards', express.static(path.join('assets/data/img/cards')));
app.get('/', function (req, res) {
   res.send('Hello World');
});

module.exports = app;

我的server.js

const app = require('./index');
const config = require('./config');
//Mysql connection
const mysql = require('mysql');



app.listen(config.express.port, function() {
    console.log(`Running on ${config.express.ip}:${config.express.port}`);
});


const connection = mysql.createConnection({
    host: config.mysql.host,
    user: config.mysql.username,
    password: config.mysql.password,
    port: config.mysql.port,
    database: config.mysql.database,
});

connection.connect();

connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
    if (err) throw err;
    console.log(`The solution is ${rows[0].solution}`);
});

//connection.end();


例如,我想通过localhost:3000 / resources / cards / image.png访问我的图像,但是仍然得到此Cannot GET /resources/cards

1 个答案:

答案 0 :(得分:0)

尝试通过将mount path指定为绝对值并将__dirname添加到path.join(...)

app.use('/resources/cards', express.static(path.join(__dirname, 'assets/data/img/cards')));