Reputation: 103
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.
Upvotes: 5
Views: 11228
Reputation: 366
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:
koa-static
To serve files just pass the koa-static
middleware to the koa's middleware stack with app.use()
.
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)
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)
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)
Upvotes: 11
Reputation: 184
The official method for static-file serving is https://www.npmjs.com/package/koa-static, you can see the documentation there.
Upvotes: 0
Reputation: 7777
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/")));
Upvotes: 0