简体   繁体   中英

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

I am not able to set simple Koa server, so it would allow me to have index.html and css files in different folders. Also as next step i want to have many js files in different folders. I do not know Koa. Please be so kind to provide help.

I have tried to use mount as shown in Can I have koa-static serve assets at a custom (eg, /static/) path? but it did not work

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);

I got following error: GET http://localhost:3000/src/styles/vendor.css net::ERR_ABORTED 404 (Not Found)

My file structure is as follow: MyProject ->

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) 

I expect the app to work on localhost:3000 and recognize all paths

By following your example I have created an dummy project with following structure.

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

Note that server.js is not in the src folder, they are on the same level And here is the adjusted server code, which is the same as yours except path.join part

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);

I have noticed that I could access vendor.css by typing the following url

http://localhost:45551/vendor.css

In order to have it working I have adjusted this line

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

which exposes all src folders and files, so this way I could access the styles/vendor.css file by using the following url

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM