Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set localAddress when sending HTTP requests? #6346

Open
wesfc opened this issue Apr 9, 2024 · 2 comments
Open

How to set localAddress when sending HTTP requests? #6346

wesfc opened this issue Apr 9, 2024 · 2 comments

Comments

@wesfc
Copy link

wesfc commented Apr 9, 2024

Describe the issue

I need to set my local address to be used on my request.
Is there some way to do it?

PS: I already check axios requests documentation and I know the option localAddress is not listed there.

Example Code

const options = {};
options.localAddress = <my-local-address>

return axios.post(url, location, options)
    .then((result) => {})
...

Expected behavior

I would expect to be able set my local address on HTTP requests.

Axios Version

1.6.8

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

16.20.2

OS

No response

Additional Library Versions

axios": "^1.6.8",
"express": "^4.17.1",
"fast-xml-parser": "^4.3.6",
"ioredis": "^4.17.3",
"lodash": "^4.17.15",
"log4js": "^6.3.0",
"url": "^0.11.0",
"uuid": "^9.0.0"

Additional context/Screenshots

No response

@justindhillon
Copy link

You can do it by utilizing the underlying HTTP agent in Node.js:

const agent = new http.Agent({ localAddress: '192.168.1.100' }); // Replace with your desired local address

const options = {};
options.httpAgent = agent;

return axios.post(url, location, options)
    .then((result) => {})

@karlbateman
Copy link

What I typically do is create a configurable Axios client using a factory function. Here is an example, where the fallback is a local address. Setting the environment variable HTTP_REQUEST_ADDRESS can alter where HTTP requests are made.

import axios from "axios";

function clientFactory() {
  return axios.create({
    baseURL: process.env.get("HTTP_REQUEST_ADDRESS", "http://127.0.0.1:8080"),
    timeout: 3 * 1000,
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants