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