• 请问下有办法设置user-agent吗?

我的插件这边会调用一个表情包api,但是最近api限制了userAgent,我在axios里面设置user-agent失败,报
Refused to set unsafe header "User-Agent"
放到proload.js里面也是一样的错误.发送请求的user-agent都是

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) uTools/5.1.0 Chrome/108.0.5359.215 Electron/22.3.27 Safari/537.36
接口是这个 https://doutu.lccyy.com/doutu/all?ac=home&start=0&limit=30&keyword=

我在postman里面把user-agent任意修改下就可以成功调用,所以想咨询下有没有办法设置user-agent

PS: 经过测试,很搞笑的是,只要把user-agent里面的uTools关键字改掉就可以调用成功...应该是专门限制了uTools🤣

  • dto 回复了此帖

    diduweiwu

    未经同意爬取他人数据并不可取,既然对方已经做了限制,请勿再爬取,否则可能存在违法的风险。

    虽说不可取,但也不是不能做,你在preload中调用axios,并将axios的httpAgent设置为http就可以自定义user-agent了。

    dto 嗯,他API本身是开放使用,在他首页有说明
    既然专门针对utools的调用做了限制,不用也罢了🤝

      浅梦凉城 感谢老哥指点,我试了下,preload.js里面封装axios并设置httpAgent/httpsAgent都无效.算了,他接口方既然已做限制,我还是弃用算了
      这是测试用的改造代码,F12查看仍然无法设置成功,感觉和electron或者utools环境机制有关系

      let url = 'https://doutu.lccyy.com/doutu/all?ac=home&start=0&limit=30&keyword='

      // 创建新的http和https agent
      const httpAgent = new http.Agent({ keepAlive: true });
      const httpsAgent = new https.Agent({ keepAlive: true });

      axios({
      method: 'get',
      url,
      httpAgent: httpAgent,
      httpsAgent: httpsAgent,
      headers
      }).then((response) => {
      console.log('结果是',response.data);
      }).catch((error) => {
      console.error(error);
      });

        你少了一句最核心的,所以失败了:

        axios({
        adapter: "http",
        method: 'get',
        url,
        httpAgent: httpAgent,
        httpsAgent: httpsAgent,
        headers
        }).then((response) => {
        console.log('结果是',response.data);
        }).catch((error) => {
        console.error(error);
        });

        核心就是:adapter: "http",这个指定了axios使用的是http,而不是fetch,fetch是无法设置user-agent的,但是node的http是可以的

        2 个月 后

        浅梦凉城 好的,感谢老哥指点.虽然已经放弃那个图源了,但是技术上我再去试试看😄

          你自己不会做一个反向代理来篡改user-agent吗,这么点小问题,就把你难住了。建议平台弄个接单版块,挣点外快

            说点什么吧...
            闽ICP备18007474号