首页 > 解决方案 > 尝试提供公共文件的 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并且没有拆分路由器,它似乎可以工作。

任何帮助都会很棒,如果您需要更多信息,请询问。

标签: javascriptnode.jsexpress

解决方案


尝试更改此行:

server.use(express.static(path.normalize(__dirname+'/public')));

为了:

server.use(express.static(__dirname + '/public'));

或者

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

推荐阅读