用 Node.js 搭建跨域代理,获取 Bing 每日一图
用 Node.js 搭建跨域代理,获取 Bing 每日一图

用 Node.js 搭建跨域代理,获取 Bing 每日一图

📌 目标

实现网页 HTML 能跨域请求 Bing 每日一图,通过代理服务 http://sunxiao.dpdns.org:8080/ 获取图片数据。

✅ 步骤一:安装 Node.js 和 npm

apt update
apt install -y nodejs npm
确认版本:
node -v
npm -v
建议 Node.js 版本 ≥ 14

✅ 步骤二:克隆并安装 CORS Anywhere

git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere
npm install

✅ 步骤三:使用 screen 启动后台服务

1. 启动一个新的 screen 会话:

    screen -S corsproxy

    2. 在 screen 会话中启动服务:

      node server.js --hostname 0.0.0.0 --port 8080

      启动后应看到:

      Running CORS Anywhere on 0.0.0.0:8080

      3. 使用快捷键退出 screen 会话但不关闭程序:

      • 按下:Ctrl + A 然后 D
      这会将你从 screen 中分离,服务仍在后台运行。

      4. 查看是否仍在运行:

        screen -ls

        恢复 screen 会话:

        screen -r corsproxy

        ✅ 步骤四:配置防火墙或 GCP 防火墙(如部署在云端)

        确保防火墙或云平台(如 GCP、AWS、阿里云)允许 TCP 8080 端口入站访问。

        在 GCP 上,你需要在“VPC 网络 → 防火墙规则”中添加一条:

        • 协议:TCP:8080
        • 源 IP:0.0.0.0/0
        • 目标:你的实例

        ✅ 步骤五:前端 HTML 页面示例

        将以下代码保存为 index.html,放在任意 Web 服务器上运行即可(如 nginx、Apache 或本地测试):

        <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Microsoft Bing 每日一图</title>
        <style>
        body {
        margin: 0;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        background-color: #000;
        }

        #bingImage {
        max-width: 100%;
        max-height: 100%;
        }
        </style>
        </head>
        <body>

        <img id="bingImage" alt="Bing Daily Image" />

        <script>
        // 使用CORS Anywhere代理获取每日一图信息
        async function getBingWallpaper() {
        try {
        const proxyUrl = 'http://sunxiao.dpdns.org:8080/';
        const apiUrl = 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US';
        const response = await fetch(proxyUrl + apiUrl);
        const data = await response.json();

        // 输出图像URL值
        console.log('Image URL:', data.images[0].url);

        const imageUrl = 'https://www.bing.com' + data.images[0].url;

        // 设置图片源
        document.getElementById('bingImage').src = imageUrl;
        } catch (error) {
        console.error('Error fetching Bing wallpaper:', error);
        }
        }

        // 页面加载时调用获取Bing每日一图的函数
        window.onload = getBingWallpaper;
        </script>

        </body>
        </html>

        ✅ 补充说明:重启后服务丢失怎么办?

        screen 会话不会自动重启,若系统重启后你需要:

        screen -S corsproxy
        cd cors-anywhere
        node server.js --hostname 0.0.0.0 --port 8080

        如果你希望自动启动,可以将其加入开机脚本或使用更强大的 pm2

        🎉 成功效果

        访问 index.html 后,你将看到来自 Bing 每日一图的高清背景图自动显示在网页中央。

        发表回复

        您的邮箱地址不会被公开。 必填项已用 * 标注

        Title - Artist
        0:00