2

I want to implement universal links in my project and I need to serve a json via Koa, which is a static file named apple-app-site-association.

My file is located in /assets/apple-app-site-association/apple-app-site-association folder.

My concern is that I cannot access this https://myprojectlink/apple-app-site-association.

What I have at this moment:

const path = require("path");
const Koa = require("koa");
const mount = require("koa-mount");
const serve = require("koa-better-serve");

app.use(mount("/apple-app-site-association", serve(path.resolve(__dirname,"../../../assets/apple-app-site-association/apple-app-site-association"))));

I get Not Found, it seems like I cannot serve it in the right way.

What can I do?

Thank you very much in advance.

Gina
  • 73
  • 2
  • 9

3 Answers3

9

The koa-static module is what you are looking for. You can use this to serve a single file or entire directory to a given path. Here are a couple of examples that should help:

Serving Files With koa-static

To serve files just pass the koa-static middleware to the koa's middleware stack with app.use().

Serve an Entire Directory

Here we are serving the entire /static directory

const Koa = require('koa')
const serve = require('koa-static')
const path = require('path')

const app = new Koa()
app.use(serve(path.join(__dirname, '/static')))

app.listen(3000)

Serve a Single File

Here we are serving a single file, for example, the data.json file inside of the /static directory

const Koa = require('koa')
const serve = require('koa-static')
const path = require('path')

const app = new Koa()
app.use(serve(path.join(__dirname, '/static/data.json')))

app.listen(3000)

Serve Directory or File on a Given Path

Use koa-mount to mount koa-static to a given path. For example, here we mount the entire /static directory to be served on the /public path

const Koa = require('koa')
const serve = require('koa-static')
const mount = require('koa-mount')
const path = require('path')

const app = new Koa()
app.use(mount('/public ',serve(path.join(__dirname, '/static'))))

app.listen(3000)
Dominic Egginton
  • 346
  • 2
  • 10
0

serve (koa-better-serve), like most static server middlewares for Node frameworks, takes a path to a directory, not a path to a single file. You can also get rid of the mount() call, koa-mount is for mounting other Koa apps as middleware.

app.use(serve(path.resolve(__dirname,"../../../assets/apple-app-site-association/")));

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
0

The official method for static-file serving is https://www.npmjs.com/package/koa-static, you can see the documentation there.

RuiSiang
  • 154
  • 6