relative URL not working with axios in node
Asked Answered
D

2

7

On my node server, the following code works

axios.get('http://localhost:8080/myPath') // works

But relative pathes don't work

axios.get('/myPath') // doesn't work

I get this error :

message:"connect ECONNREFUSED 127.0.0.1:80" port:80

How can I get the relative url work like in the browser ?

Relative path should be hitting on port 8080, not 80.

Where do I set that on my node server ?

Dyer answered 23/10, 2018 at 11:8 Comment(0)
H
7

Create a new instance with custom configuation. like below

var instance = axios.create({ baseURL: 'http://localhost:8080' });

instance.get('/myPath', { timeout: 5000 });

Hope, this will works Reference: https://www.npmjs.com/package/axios

Horizontal answered 23/10, 2018 at 11:30 Comment(1)
Rather than hard-coding the basURL, you could get the origin from the request header (i.e. req.headers.origin)Shirleeshirleen
B
2

You can't use a relative URL in this scenario because there's nothing for it to be relative to - you're executing code in a script running on the server, not in a browser. It doesn't have any concept of a "current" URL to be relative to.

You'll need to explicitly specify the full domain name and port. If this causes you a problem (e.g. because you want to deploy this to different hosts without changing the code) you'll have to inject the values into your code another way (e.g. by reading from a config file, cf. documentation here).

Breeches answered 23/10, 2018 at 11:16 Comment(2)
"something on a different port" — It isn't on a different port. There isn't anything to be relative to. The code isn't running in a browser.Suffice
@Suffice ah ok so we're talking about the code executing server-side in a node environment. Sorry, I missed that part somehow. Will amend the answer.Breeches

© 2022 - 2024 — McMap. All rights reserved.