通过 Netlify function 随机展示 Unsplash 上的图片
我本意是想通过 Netlify function 在线获取网易云音乐中“我喜欢”歌单,然后生成网页的,后来发现行不通。但是,又想温习一下 Netlify function 的用法。于是,就有了如题所说的内容。现在你可以通过 https://tianheg.co/.netlify/functions/unsplash 体验。
完整配置
netlify.toml
:
1[build]
2functions = "functions"
3
4[context.production.environment]
5 NODE_VERSION = "18.12.1"
6
7[functions]
8 node_bundler = "esbuild"
9
10[[plugins]]
11package = "@netlify/plugin-functions-install-core"
functions/unsplash.js
:
1import serverless from "serverless-http"
2import { createApi } from "unsplash-js";
3import nodeFetch from 'node-fetch';
4import express from 'express'
5
6const unsplash = createApi({ accessKey: process.env.ACCESS_KEY, fetch: nodeFetch })
7
8const app = express()
9const PORT = 3000
10
11app.get('/.netlify/functions/unsplash/', (req, res) => {
12 unsplash.photos.getRandom()
13 .then(json => {
14 let imageUrl = json.response.urls.regular;
15 res.send(`<img src="${imageUrl}">`)
16 })
17})
18
19app.listen(PORT, () => {
20 console.log(`Unsplash app listening on port ${PORT}`)
21})
22
23exports.handler = serverless(app)
在 Web 端要添加环境变量 ACCESS_KEY
。如何获取 ACCESS_KEY?答案在这里。
参考资料