[英]How to use express.static in none app.js folder?
I am trying to show the image by using express.static from a server side. 我试图通过从服务器端使用express.static来显示图像。
my folder is structure like this.. 我的文件夹是这样的结构..
public
/test.png
routes
/index.js
/upload.js
app.js
express.static works under app.js ( http://localhost:4000/img/test.png ) app.js下的express.static工作( http:// localhost:4000 / img / test.png )
const express = require('express');
const app = express();
app.use('/img', express.static(__dirname + '/public'));
// Server Listen
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
but it doent work under upload.js ( http://localhost:4000/img/test.png ) what am i doing wrong here? 但它在upload.js( http:// localhost:4000 / img / test.png )下工作,我在这里做错了什么? the path seems to be the right one by consoling.
通过安慰,这条道路似乎是正确的道路。
upload.js upload.js
const express = require('express');
const upload = express.Router();
const cors = require('cors');
const path = require("path");
upload.use(cors());
console.log(path.join(__dirname + '/../public'));
upload.use('/img', express.static(path.join(__dirname + '/../public')));
module.exports = upload;
Here are my index.js and app.js 这是我的index.js和app.js
index.js index.js
const router = require('express').Router();
const uploadRoutes = require('./upload');
router.use('/upload', uploadRoutes);
module.exports = router;
app.js app.js
// Import thrid parties for APP
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const routes = require('./routes');
// App configuration
app.use(bodyParser.json());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
// Route Configuration
app.use('/api', routes);
// Server Listen
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
thank you for looking over this. 谢谢你的看法。
我认为它应该像app.use('/img', express.static(__dirname + 'public'));
It isn't necessary to use express.static
in both files. 没有必要在两个文件中使用
express.static
。 It's typically put in the entry file (app.js). 它通常放在条目文件(app.js)中。
Here's an example from the express docs (notice that the /
isn't necessary): 以下是快速文档中的示例(注意
/
不是必需的):
app.use('/static', express.static(path.join(__dirname, 'public')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.