const express = require('express');
const axios = require('axios');
const app = express();

const cors = require('cors');
app.use(cors());

// 中间件，用于解析 JSON 请求体
app.use(express.json());

// 接口路由
app.post('/process-urls', async (req, res) => {
  try {
    const { urlArr } = req.body;
        
    if (!urlArr || !Array.isArray(urlArr)) {
      return res.status(400).json({ error: 'urlArr 必须是一个数组' });
    }

    const requests = urlArr.map(url => {
      return axios.get(url, {
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
          'Referer': 'https://mp.weixin.qq.com/',
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
        }
      })
    	.then(res => ({
        url: url,
        data: res.data
      }))
      .catch(error => ({
        url: url,
        error: error.message
      }));
    });

    const results = await Promise.all(requests);
        
    // 过滤掉没有数据的项
    const contents = results.filter(item => item.data);
        
    res.json({ contents });
  } catch (error) {
    console.error('处理请求时出错:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// 启动服务器
const PORT = 3300;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});