user3568719
user3568719

Reputation: 1056

set user agent in a node request

I try to set user agent to a npm request. Here is the documentation, but it gives the following error:

Error: Invalid URI "/"

const request = require('async-request')

const run = async (url) => {
  const {statusCode} = await request(url)
  console.log(statusCode) // 200, works
  const options = {
    url,
    headers: { 
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    }
  }
  await request(options) // Error: Error: Invalid URI "/"
}

run('https://github.com/')

sandbox

I also tried request.get, as it mentioned in here, but it gives "request.get is not a function" error.

Upvotes: 1

Views: 792

Answers (1)

Darth
Darth

Reputation: 1651

The problem is you are looking at the documentation of request, but using the async-request, which dont support calling with the object argument like you do.

const request = require('async-request')

const run = async (url) => {
  const {statusCode} = await request(url)
  console.log(statusCode) // 200, works
  const options = {
    headers: { 
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    }
  }
  
  const res = await request(url, options);  
  console.log(res.statusCode) // 200, works
}

run('https://github.com/')

Upvotes: 3

Related Questions