Search code examples
node.jsipfetch-api

How to set localAddress in fetch request in node.js?


On my server i have multiple ip addresses. I need to make API call from my node.js server to external service, but i need to make it from specific ip address each time (the ip depend on many factors).

it seems that HTTP module of node support localAddress property to specify from what ip address send the request but some library I import use the fetch method.

How i can tell fetch method to make http request from a specific ip address?


Solution

  • If by fetch in Node.js you mean node-fetch npm module, then, judging by the fact that it interprets it's own options object and builds an entirely different one for the http.get request it wraps (all so that it can match the WHATWG Fetch Specification more fully), unfortunately it's impossible. Furthermore, this functionality would/could never be part of any browser API.

    You can, however use the localAdress in options object with got npm module, which is a much more transparent Promise wrapper around http.request.

    More details about the syntax:
    https://www.npmjs.com/package/got https://nodejs.org/api/http.html#http_http_request_options_callback