通过 Netlify function 随机展示 Unsplash 上的图片

我本意是想通过 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?答案在这里

参考资料

欢迎通过「邮件」或者点击「这里」告诉我你的想法
Welcome to tell me your thoughts via "email" or click "here"