Koa - 错误,找不到文件 - 当 html 和 css 位于不同的文件夹中时

Koa - error, file not found - when html and css are in different folders

我无法设置简单的 Koa 服务器,所以它允许我在不同的文件夹中有 index.html 和 css 文件。另外作为下一步,我想在不同的文件夹中有许多 js 文件。我不知道Koa。请提供帮助。

我曾尝试使用 中所示的挂载,但没有成功

const path = require('path');
const Koa = require('koa');
const koaStatic = require('koa-static');
const getPort = require('get-port');

async function runServer() {
    const port = await getPort({ port: 3000 });

    const app = new Koa();
    app.use(koaStatic(path.join(__dirname, '..', 'src/static')));
    app.use(koaStatic(path.join(__dirname, '..', 'src/styles')));

    app.listen(port);

    console.log(`server started at http://localhost:${port}/`);
}

runServer().catch(console.error);

我收到以下错误:GET http://localhost:3000/src/styles/vendor.css net::ERR_ABORTED 404(未找到)

我的文件结构如下: 我的项目 ->

src-> components (header.component.js, footer.component.js)
src-> services (service.js)
src-> assets (data.json)
src-> scripts (some-js-files.js)
src-> styles (styles.css)
src-> static (index.html) 

我希望该应用能够在 localhost:3000 上运行并识别所有路径

按照您的示例,我创建了一个具有以下结构的虚拟项目。

~/src -
 | - static
 | - styles
     |- index.html
     |- vendor.css
~/server.js

注意server.js不在src文件夹中,他们在同一层 这是调整后的服务器代码,除了path.join部分

外,与您的代码相同
const path = require('path');
const Koa = require('koa');
const koaStatic = require('koa-static');
const getPort = require('get-port');

async function runServer() {
  const port = await getPort({ port: 3000 });

  const app = new Koa();
  app.use(koaStatic(path.join(__dirname, 'src/static')));
  app.use(koaStatic(path.join(__dirname, 'src/styles')));

  app.listen(port);

  console.log(`server started at http://localhost:${port}/`);
}
runServer().catch(console.error);

我注意到我可以通过键入以下 url

来访问 vendor.css

http://localhost:45551/vendor.css

为了让它正常工作,我调整了这一行

app.use(koaStatic(path.join(__dirname, 'src')));

它公开了所有 src 文件夹和文件,因此我可以使用以下 url

访问 styles/vendor.css 文件

http://localhost:33717/styles/vendor.css