0

My app is in Koa JS.

The code below generates a website with full css (http://localhost:3000/product):

module.exports = (router, productsLoader) => {
  router.get("/product", async ctx => {
    const product = await productsLoader.single(ctx.params.slug)
    ctx.state.model = {
      title: 'Hey there,',
      products: product
    }
    await ctx.render('product');
  })
}

However if I add a key (:slug) to the url, the website can show the bare content but not any css features (http://localhost:3000/product/abc):

module.exports = (router, productsLoader) => {
    router.get("/product/:slug", async ctx => {
      const product = await productsLoader.single(ctx.params.slug)
      if (product) {
         ctx.state.model = {
         title: product.name,
          product: product
        }
        await ctx.render('product')
      }
    })
  }

My intuition tells me it is something to do with async and await, but I couldn't find out exactly what went wrong.

edit:

In the website below, it said "So CSS doesn't get sent along with the pages in a dynamic site like this. The HTML gets sent to the client, and then the client requests the files from the server. So what I did was I added a router to the CSS in my app.js" & "But on a dynamic site, when a request is made, and a response is sent, the response is sent to the '/', and NOT to the subfolder that's on the server side (at least by default). There is no subfolder on the client's side. Responses are simply just sent to the '/' by default. So make sure that the HTML is referencing the client side's files, and not the server side's files!"

But if I have lots of css files to reference to, then that means I have to manually reference to those files again? that sounds quite counter intuitive as Koa Js is supposed to be more convenient!

https://teamtreehouse.com/community/cant-get-the-css-to-load-in-the-nodejs-server

Alex Luk
  • 41
  • 9
  • you should show us your view, also what is the `await {}` in your first example, and lastly what is the url you hit that shows the error ? – Gabriele Petrioli Jun 04 '20 at 21:57
  • Keep in mind that in the second example you only call `await ctx.render('product')` if a product is found from the `productsLoader.single` becuase the `render` is inside the `if`. – Gabriele Petrioli Jun 04 '20 at 22:04
  • I have updated my code. Regarding your 2nd question, the product was found because otherwise there would be an error page saying "no found". in this case however, the page product.pug is shown but all the css are not loaded. it is shown as a plain text page. No error is shown in the console either. – Alex Luk Jun 05 '20 at 09:24

0 Answers0