How to serve the same static files regardless of the route?

六眼飞鱼酱① 提交于 2019-12-24 11:34:59

问题


I have a react App. With webpack I build for production. Now I try to set a little koa server to serve the static files generated by webpack for production.

So I did this

import Koa from 'koa'
import serve from 'koa-static'

const app = new Koa()

app.use(serve('dist/'))

app.listen(3001)

Where dist/ is the directory where are the files (index.html, bundle etc). This works well but only for the route '/' (localhost:3001/) In my app I use react router so I need to go to /login (localhost:3001/login) by example. But when I try I get "Not Found". With the devServer (by webpack) this route works well. I just need to always serve /dist, whatever the route. How to do this whit koa ?


回答1:


One option is to intercept the react-router client routes in Koa and rewrite them to '/' to load index.html and the client assets.

const REACT_ROUTER_PATHS = [
  '/login',
  '/logout',
  '/other-client-path'
];

app
  .use(async (ctx, next) => {
    if (REACT_ROUTER_PATHS.includes(ctx.request.path)) {
      ctx.request.path = '/';
    }
    await next();
  })
  .use(serve('dist/'));



回答2:


If koa is like express-static it is normal that he returns 'Not Found' because the only file present is 'index.html'. My solution

import fs from 'fs';


app.use(serve('dist/'));
// If the file is not found by koa
// intercept all request and return index.html
// this way you can manage the request in React 
app.use((ctx, next) => {
    ctx.type = 'html';
    ctx.body = fs.readFileSync('./dist/index.html');
});



回答3:


Ok I finally won

import Koa from 'koa'
import serve from 'koa-static'
import fs from 'fs'
import path from 'path'

const app = new Koa()
const dist = path.join(__dirname, 'dist')
let validRoutes

fs.readdir(dist, (err, files) => {
  if (err) return console.log('Unable to scan directory: ' + err)
  validRoutes = files
})

function isRouteValid (url) {
  if (!validRoutes || !url) return false
  return validRoutes.find(route => url.slice(1) === route)
}

app.use(async (ctx, next) => {
  if (!isRouteValid(ctx.url)) ctx.path = 'index.html'
  await next()
})

app.use(serve(dist))

app.listen(3010)


来源:https://stackoverflow.com/questions/52462160/how-to-serve-the-same-static-files-regardless-of-the-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!