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

正在阅读下面文章的是一个七岁的孩子,你该如何表达才能让他理解以下技术内容?(费曼学习法

你要解决的最重要问题是什么?

一个 AI 文本生成工具——Teach Anything,辅助教授别人当前篇目概念

我本意是想通过 Netlify function 在线获取网易云音乐中“我喜欢”歌单,然后生成网页的,后来发现行不通。但是,又想温习一下 Netlify function 的用法。于是,就有了如题所说的内容。现在你可以通过 https://tianheg.xyz/.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?答案在这里

参考资料




如希望撰写评论,请发邮件至 me@tianhegao.com (直接点击邮箱可自动跳转至默认邮箱App,并填写收信人和邮件主题)或者点击这里在线留言,我会挑选对读者有价值的评论附加到文章末尾。



可通过以下渠道赞赏此文