You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Express实现前端向后端动态传URL并返回爬虫结果?

实现Express动态接收URL并返回维基百科爬虫结果

核心修改思路

你原来的代码是提前爬取固定URL后才启动服务,只能返回单一结果。要实现动态接收前端传入的URL,需要把服务启动、路由定义和爬虫逻辑拆开,让每个请求都独立处理新的目标URL。

修改后的完整代码

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

const app = express();
const port = 3000;

// 配置JSON解析中间件(使用POST传参时需要)
app.use(express.json());

// 定义爬虫接口,通过GET参数接收目标URL
app.get('/scrape', async (req, res) => {
    try {
        // 从请求参数中获取前端传入的URL
        const targetUrl = req.query.url;
        
        // 校验URL是否提供
        if (!targetUrl) {
            return res.status(400).send('请传入要爬取的维基百科URL');
        }

        // 请求目标页面内容
        const axiosRes = await axios.get(targetUrl);
        if (axiosRes.status !== 200) {
            return res.status(500).send('无法获取目标页面内容');
        }

        // 使用cheerio处理页面(替换成你的实际解析逻辑)
        const $ = cheerio.load(axiosRes.data);
        // 示例:提取页面标题和第一段内容
        const pageTitle = $('h1').text().trim();
        const firstParagraph = $('p').first().text().trim();
        const result = {
            title: pageTitle,
            content: firstParagraph
        };

        // 返回处理后的结果
        res.status(200).json(result);
    } catch (error) {
        // 捕获异常并返回错误信息
        res.status(500).send(`处理失败:${error.message}`);
    }
});

// 启动服务
app.listen(port, () => {
    console.log(`服务运行在端口 ${port}`);
});

关键说明

  1. 服务启动时机:把app.listen()放在最外层,确保服务一开始就启动,随时可接收前端请求。
  2. 动态URL传递:用req.query.url获取前端通过GET方式传递的URL(比如前端请求http://localhost:3000/scrape?url=https://en.wikipedia.org/wiki/Yeti_Airlines_Flight_691)。如果想用POST方式,前端可将URL放在请求体中,后端通过req.body.url获取,需确保已配置app.use(express.json())。
  3. 错误处理:添加了参数校验、请求状态判断和全局异常捕获,避免服务崩溃,同时给前端明确的错误反馈。
  4. 爬虫逻辑隔离:每次请求都会重新发起axios请求和cheerio解析,保证每个请求处理的都是前端传入的最新URL。

前端调用示例

  • GET请求方式:
    fetch('http://localhost:3000/scrape?url=https://en.wikipedia.org/wiki/Yeti_Airlines_Flight_691')
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    
  • POST请求方式:
    fetch('http://localhost:3000/scrape', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ url: 'https://en.wikipedia.org/wiki/Yeti_Airlines_Flight_691' })
    })
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    

内容的提问来源于stack exchange,提问作者Tribe56123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:25:58