Skip to content
Advertisement

How to Inject Axios in Puppeteer

I want to inject axios in puppeteer in order to open a browser session, but sending requests and receiving responses through axios:

So the question is, is it possible? Here’s my attempt, but it is not working since axios doesn’t intercepts the website responses

const axios = require('axios');
const puppeteer = require ('puppeteer');

(async () =>{
    const browser = await puppeteer.launch({headless:false})
    const page = await browser.newPage()
    await page.goto('https://InstanceOfUrl.com/something.php')
    const res = await axios.get('https://InstanceOfUrl.com/something.php?action=examples/foo')
    const data = res.data
    console.log(data)
})()

I’m moving my first steps in axios, so I beg you to be patient; Thanks for your help in advance

Advertisement

Answer

I encourage you to go into a more verbose version using Promises:

  • combining with @Simon’s advise using fetch
puppeteer
  .launch({headless:false})
  .then(browser => browser.newPage())
  .then(page => page.goto('https://InstanceOfUrl.com/something.php'))
  .then(() => fetch('https://InstanceOfUrl.com/something.php?action=examples/foo')
  .then(data => console.log(data))
  .catch(error => {
    throw new Error(error.message);
   })
  .finally(() => browser.close());

This will allow you to reason about each object passed into the next .then in the promise chain.

Hope it helps

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement