javascript - 尝试提供公共文件的 Express API 给出 404
问题描述
我目前有这样的 API 设置......
index.js
require('dotenv').config();
const index = require('./server');
const port = process.env.PORT || 5000;
index.listen(port, () => console.log(`Server is live at localhost:${port}`));
module.exports = index;
服务器/index.js
const express = require('express');
const routes = require('../routes');
const bodyParser = require('body-parser');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const server = express();
server.use(express.json());
// enhance your server security with Helmet
server.use(helmet());
// use bodyParser to parse server application/json content-type
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
// log HTTP requests
server.use(morgan('combined'));
server.use(express.static(path.normalize(__dirname+'/public')));
server.use('/api', routes);
// Handle 404
server.use(function(req, res) {
res.send('404: Page not Found', 404);
});
// Handle 500
server.use(function(error, req, res, next) {
res.send('500: Internal Server Error', 500);
});
module.exports = server;
路线/index.js
const router = Router();
// enable all CORS requests
router.use(cors());
router.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.get('/', (req, res) => res.send('Welcome to Timelapse Videos API'));
....
出于某种原因,我的公共目录总是返回 404,我不知道为什么。
如果我将它添加到routes/index.js:
router.get('/public', function(req, res) {
res.sendFile(path.join(path.normalize(__dirname+'/../public'), 'index.html'));
});
它将返回静态文件,但问题是,可能有许多客户目录有我想要返回的多个图像。
我的设置显然存在问题,但我可以一辈子看看发生了什么。如果我在index.js中有一个 API并且没有拆分路由器,它似乎可以工作。
任何帮助都会很棒,如果您需要更多信息,请询问。
解决方案
尝试更改此行:
server.use(express.static(path.normalize(__dirname+'/public')));
为了:
server.use(express.static(__dirname + '/public'));
或者
server.use(express.static('public'));
推荐阅读
- java - 检查包含路径参数的两个 URL 的相等性
- jquery - jquery缩小版本更新后facebook feed未加载
- python - 测试 opencv 的调整大小功能,但我不断收到此错误
- python - RuntimeError:张量 a (64) 的大小必须与非单维 3 的张量 b (128) 的大小相匹配
- java - 我无法使用我的 java 代码建立从 sftp 服务器到本地计算机的连接
- python - 想要为人工神经网络设计定制的 Step 激活函数
- javascript - 为什么我的代码适用于箭头函数并被绑定破坏?
- node.js - 如何在不使用 Azure 服务的情况下将 Whatsapp 与 Power 虚拟代理集成?
- python-3.x - 我想找到多个相似矩阵生成算法来输入光谱聚类作为它的邻接矩阵
- node.js - 如何使用 npm 安装 bcrypt?