netlify随机图片api

前言

原先准备用在随机背景图片的,参考:Hexo_Fluid 随机背景图实现

以为 fluidbanner 可以使用 api

所以研究了下,写了个云函数,后续回看 fluid 文档才发现 banner 不能使用 apiwtf….

现在单纯记录下文件结构和代码后删除文件和站点

参考资料

  • 搜索关键字
    • vercel+自建+返回随机图片+api
    • netlify+自建+返回随机图片+api

文件结构

1
2
3
4
5
6
7
rangeImage
├── image
└── netlify
└── functions
└── rangeImage
├── image
└── rangeImage.js

说明下为什么有两个 image 文件夹

这里说明下,免得到时候疑惑
const files = fs.readdirSync('./image') 这里不管怎么写
部署到 netlify 后都不行,一直提示找不到,具体两个情况

放在根目录下,可以通过网址访问的到,但是函数脚本怎么设置都访问不到,本地测试了是可以的,例如 ('../../../image'),但是一部署到服务器上就不行了,提示找不到

另外一种,放在跟脚本一起,这样脚本访问的到,但是网址访问不到,没有网址可以提供给外部

所以秉持完成目的优先,直接创建 2 份一份根目录、一份跟脚本一起解决这个问题

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Docs on event and context https://docs.netlify.com/functions/build/#code-your-function-2

const fs = require('fs');
const path = require('path');

const handler = async (event) => {
// 检查请求的来源域名
const { headers } = event;
const requestOrigin = headers.origin || headers.Origin || '';

// if (requestOrigin !== 'https://www.linguoguang.com') {
// return {
// statusCode: 403,
// headers: {
// 'Content-Type': 'application/json',
// 'Access-Control-Allow-Origin': 'https://www.linguoguang.com',
// },
// body: JSON.stringify({ error: 'Access denied.' }),
// };
// }


try {
// 读取图片目录下的所有图片文件
// const __dirname = path.resolve();
const files = fs.readdirSync('./image');


// 随机选择一张图片
const randomIndex = Math.floor(Math.random() * files.length);
const randomImage = files[randomIndex];

// 返回图片的URL
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': 'https://www.linguoguang.com',
},
body: JSON.stringify({
image: `https://scintillating-pixie-b4c42c.netlify.app/image/${randomImage}`,
}),
};
} catch (error) {
console.log(error);

// 返回错误消息
return {
statusCode: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Origin': 'https://www.linguoguang.com',
},
body: JSON.stringify({
error: 'An error occurred while fetching the random image.',
}),
};
}
}

module.exports = { handler }

请求结果

请求后,返回随机的图片 url

Pasted image 20230511005847


netlify随机图片api
https://linguoguang.com/2023/05/11/netlify随机图片api/
作者
linguoguang
发布于
2023年5月11日
许可协议