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

Setting baseURL in default configuration #175

Closed
nathanharper opened this issue Dec 15, 2015 · 27 comments
Closed

Setting baseURL in default configuration #175

nathanharper opened this issue Dec 15, 2015 · 27 comments

Comments

@nathanharper
Copy link

In some cases my app requires different defaults from the standard ones, and I've been dealing with this by putting something like this in the app's entry point:

let axiosDefaults = require('axios/lib/defaults');
axiosDefaults.baseURL = 'http://somesite.com';

My tests are run in Node and I want to override the baseURL so that axios will work with Nock even with relative URLs, but the code above doesn't work. Would it be reasonable to add this parameter to the defaultConfig when instantiating Axios? Or is there a better way I should be doing this? I have an example of what I mean here.

@mzabriskie
Copy link
Member

This sounds like a bug. I will have to dig in a bit deeper to confirm, but at a glance the code looks problematic. The Axios constructor holds onto a defaultConfig for each instance. Which means that if axios.defaults ever changes the default instance won't be modified.

@mzabriskie mzabriskie added the bug label Dec 17, 2015
@nickuraltsev
Copy link
Member

@mzabriskie Right, but what's the point in making defaults "mutable"? If you need to use custom config, you can just pass it to the Axios constructor.

@nathanharper
Copy link
Author

@nickuraltsev But in that case every time you require axios you would need to call the constructor with the baseURL option, right? I was hoping for a way to override the defaults for my entire project.

@mzabriskie
Copy link
Member

I agree that config should be immutable for custom instances, but for the default axios instance changes to axios.default should change the config internally held by that instance.

To resolve this I think the defaults should be passed to the Axios constructor for the axios instance. Then change to axios.defaults = axios.defaultConfig so that modification will actually mean something.

@nickuraltsev
Copy link
Member

@mzabriskie That makes sense. There are some differences between the structure of defaults and config though. For example:

// defaults
{
  headers: {
    common: {
      'Accept': 'application/json, text/plain, */*'
    },
    patch: utils.merge(DEFAULT_CONTENT_TYPE),
  }
}
// config
{
  headers: {
    'X-Custom-Header': 'foobar'
  }
}

@nickuraltsev
Copy link
Member

@nathanharper One solution is to create a small module like this:

// client.js

var axios = require('axios');

var axiosInstance = axios.create({
  baseURL: 'https://domain.com/foo/bar',
  /* other custom settings */
});

module.exports = axiosInstance;

and then use this new module in your code instead of requiring axios directly:

var client = require('./client');

client.get('relative/path')

@mzabriskie
Copy link
Member

@nickuraltsev you're correct that there is a difference between defaults and config. However axios.defaults should effect the config of the default axios instance in the case that no config is provided to override defaults. The problem with the current implementation is that defaultInstance = new Axios() is called the first time axios = require('axios') is called, before any chance is allowed to override axios.defaults. In this case axios.defaults should be mutable to allow developer to override default config.

@nickuraltsev
Copy link
Member

@mzabriskie What if don't merge the defaults and defaultConfig in the constructor? We can merge the defaults, defaultConfig, and the request config in the request method instead. Thoughts?

@mzabriskie
Copy link
Member

This should be resolved with #183

@nathanharper
Copy link
Author

Awesome, that fixed my problem. Thanks for the fast turnaround on this!

@mzabriskie
Copy link
Member

Glad it works for you. I'll work on getting a new release out this week.

@rkmax
Copy link

rkmax commented Mar 3, 2016

@mzabriskie this bug was fixed on the 0.9.1 version? because I'm experiencing it

I have a small module

import axios from 'axios'

export default () => {
  // __API__ = http://api.service.com
  return axios.create({baseUrl: __API__})
}

later when I use I got a wrong baseUrl

import client from '/rest-module'
// request is made to http://localhost:3000/relative/path
client().post('relative/path')

@rkmax
Copy link

rkmax commented Mar 3, 2016

never mind! I realize I'm using the wrong property baseUrl instead baseURL

@batusai513
Copy link

@nathanharper were you able to intercept axios requests with nock?

@chibicode
Copy link

@batusai513 I'm stuck trying to intercept axios requests with nock. This:

nock(...)
  .log(console.log)

always says it didn't match. I swapped axios w/ isomorphic-fetch and it starts matching...

@chibicode
Copy link

@batusai513 could be an issue w/ this (nock's matching against OPTIONS instead of POST)
#225

@batusai513
Copy link

@chibicode to bad, i use axios because the request and response interceptors, it would be cool to be able to use nock with this library

@nathanharper
Copy link
Author

@batusai513 I did manage to get nock to work with axios after this update got merged. Are you still having issues?

@batusai513
Copy link

@nathanharper yeah, i tried with v 0.10 and the test still hit the endpoint :/

@batusai513
Copy link

@nathanharper can you show me some gist of how you are implementing nock with axios, thanks.

@monday1994
Copy link

I have got following axios instance configuration:
let axiosInstance = axios.create({
baseURL: config.serverUrl
//where serverUrl i just my deployed server address 'http://myaddress.com'
});
module.exports = axiosInstance;

As you can see I am using correct format of baseURL (I mean URL instead of Url) but when I try to make simple get request to server I've got following base url http://localhost:3000/http://myaddress.com.
Can you tell me why ?

@yasharma
Copy link

yasharma commented Jul 12, 2017

import axios from 'axios'
window.axios.defaults.headers.common = {'X-Requested-With': 'XMLHttpRequest'}
window.axios.defaults.baseURL = (process.env.NODE_ENV !== 'production') ? 'http://localhost:9000/api/' : ''

This is also working, you can also do like this, i also want to know that is it correct way to do??

aqualaguna added a commit to aqualaguna/axios that referenced this issue Aug 4, 2017
this is beginner mistake. please fix it
@blanet
Copy link

blanet commented Oct 23, 2017

@monday1994 Did you solved it yet? I met the same problem, an extra "http:" inserted in my url...

@Femina
Copy link

Femina commented Jul 24, 2018

How can we use this with CORS ?

@juanr2001
Copy link

juanr2001 commented Oct 10, 2018

Too late, but the way you can set only the root URL to baseURL like this

 var url = ''
  if (process.env.NODE_ENV === 'development') {
    url = 'your domain' // you must hardcode it somewhere. In production you don't.
  }
  {
...
  baseURL: url + '/' // in production the url variable will be set to the root url of your domain. '/' forces        the basedURL to only use the root url with NO endpoints.
}

@lauri108
Copy link

lauri108 commented Nov 19, 2018

How can we use this with CORS ?

@Femina if you've got the Authorization: Bearer header in your API requests, you need to add the Access-Control-Allow headers into your API. For example, Node.js and Express it's like this:

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept")
res.header("Access-Control-Allow-Methods", "GET,POST")
next()
})

in the application's entry file.

@efillman
Copy link

For anyone still coming to this page for help with baseURL as the README states:

// baseURL will be prepended to url unless url is absolute.

essentially you must have a FQDN ie http:// or https:// in baseURL in order for it NOT to concatenate with the referrer URL (which to me is the desired behavior most people are looking for on this thread). Took me a few hours to sort that one.

@axios axios locked and limited conversation to collaborators May 21, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet