0

I have a simple HTTP request with javascript that uses the await feature, however, I get the following result:

{} undefined

When I run the function, I have tested the headers and url with python and it works successfully with requests am I missing something here?

import pkg from 'superagent';
const { get } = pkg;

const header =  {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15'
};
const url =  'https://books.toscrape.com';

class Agent {
    constructor(url, headers){
        this.url = url;
        this.headers = headers;
        
    }
    
    getAgent = async () => {
        const res = await get(this.url)
            .set(this.headers);
            return res.body;
    }
};

const request = new Agent(url, header);

console.log(await request.getAgent());

I.e. this works successfully in python:

import requests

header =  {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15'
};
url =  'https://books.toscrape.com';

print(requests.get(url, header).content)
Working dollar
  • 306
  • 2
  • 10
  • `getAgent()` doesn't *return* anything, it just logs a value to the console. It's not clear to me which you want to do... Do you want `getAgent()` to internally log its value to the console, or do you want it to return its value and consuming code log it to the console? – David Sep 28 '22 at 14:02
  • @David I prefer to return its value and consume code log to the console. – Working dollar Sep 28 '22 at 14:14
  • Then `return res.body` instead of `console.log(res.body)` ? To return something from a function, one uses the `return` statement. – David Sep 28 '22 at 14:15
  • @David sure, I have tested this before however it returns nothing when I await it with the outer console.log – Working dollar Sep 28 '22 at 14:17
  • 1
    Can you provide a runnable [mcve] which demonstrates this? In the code shown it's not returning anything simply because it doesn't `return` anything. – David Sep 28 '22 at 14:18
  • @David updated the post – Working dollar Sep 28 '22 at 14:20
  • @David I am very new to Javascript so I may be missing simple syntax here – Working dollar Sep 28 '22 at 14:21
  • 1
    Don't use an arrow function for methods, they don't receive `this`. – Barmar Sep 28 '22 at 14:38
  • Does this answer your question? [Methods in ES6 objects: using arrow functions](https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions) – EssXTee Sep 28 '22 at 15:07
  • @EssXTee No this is not the error I am getting, In fact I do not get an error, I just get an empty list returned. I have tried Barmar suggestion and still an empty list. Although the suggestion was very helpful as it did jog my memory for `this`, I remember this during a codeacademy class months ago. – Working dollar Sep 28 '22 at 15:22

0 Answers0