DOYEONG
DOYEONG

Reputation: 1

needle.get() method not working in NestJS. Any solutions?

I'm implementing Instagram social login. I want to get username and profile image, but Instagram API no longer supports only username.

I tried to get the meta [property="og:tle"] and meta [property="og:image"] of Instagram through web crawling through cheerio. It worked fine on the local backend, but could not get the information from the deployed backend. I found out that cheerio could not retrieve information such as meta [property="og:tle"], and introduced it through information that could be solved through needle, but the following error occurred.

error TypeError: Cannot read properties of undefined (reading 'get')

My code is

successfully working in the local backend, but I cannot get it to work in the deployed backend.

import { Controller, Get } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import axios from 'axios';
import cheerio from 'cheerio';
import needle from 'needle';

@Controller()
export class AppController {
  constructor() {}

  @Get()
  async getUser() {
    async function getProfileImage(username) {
      try {
        const response = await axios.get(
          `https://www.instagram.com/${username}/`,
        );

        const $ = cheerio.load(response.data);
        const fullName = $('meta[property="og:title"]')
          .attr('content')
          .split('•')[0];
        const _username = fullName.split(' ')[0].trim();
        const userId = fullName.split(' ')[1].trim().slice(2).slice(0, -1);

        const profileImageUrl = $('meta[property="og:image"]').attr('content');
        return { name: _username || userId, profileImageUrl };
      } catch (error) {
        console.error('Error:', error);
        return null;
      }
    }

    
    const username = 'example'; 
    getProfileImage(username)
      .then((profileInfo) => {
        if (profileInfo) {
          console.log('profile Info', profileInfo);
        } else {
          console.log('Cannot get Profile Info');
        }
      })
      .catch((error) => console.error('Error:', error));
  }
}

and code modified to needle

import { Controller, Get } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import axios from 'axios';
import cheerio from 'cheerio';
import needle from 'needle';

@Controller()
export class AppController {
  constructor() {}

  @Get()
  async getUser() {
    async function getProfileImage(username) {
    const results = [];
      try {
      needle.get(
        encodeURI(`https://www.instagram.com/${username}/`),
        function (err, res) {
          if (err) throw err;
          const $ = cheerio.load(res.body);
          const title = $('meta[property="og:title"]').attr('content');
          results.push({
            title: title,
          });
          console.log('results', results);
        },
      );
    } catch (e) {
      console.log('error', e);
    }
    
    const username = 'example'; 
    getProfileImage(username)
      .then((profileInfo) => {
        if (profileInfo) {
          console.log('profile Info', profileInfo);
        } else {
          console.log('Cannot get Profile Info');
        }
      })
      .catch((error) => console.error('Error:', error));
  }
}

But I got an error log error TypeError: Cannot read properties of undefined (reading 'get').

How can I get meta[property="og:title"] and some? And why doesn't it work?

Or if there is any other way to get the username and profile image of an instagram account, please let me know.

Upvotes: 0

Views: 62

Answers (0)

Related Questions