2

I want to use relative paths in my code, so I need to set baseUrl parameter in axios. Setting it in global Axios object works, but on instance doesn't (it is requesting like there was no baseUrl set). I would be glad to know why:)

Thanks in advance.

import React, { Component } from 'react';
import Axios from 'axios';

Axios.defaults.baseURL = "http://localhost:3000";
let instance = Axios({
  baseUrl: 'http://localhost:3000'
});

class CardViewer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      cards: []
    }
  }

  componentDidMount() {
    // instance.get('/cards').then(response => {
    //   this.setState({
    //     cards: response.data
    //   });
    // }); doesn't working
    Axios({
      method: 'get',
      url: '/cards'
    }).then(response => {
      this.setState({
        cards: response.data
      })
    });
  }

  render() {
    let cardsElements = this.state.cards.map(card => 
    <div className="card my-1 col-6 mx-auto" key={card.id}>
      <div className="card-body">
        <div className="card-title">{card.author}</div>
        <div className="card-text">{card.text}</div>
      </div>
    </div>);

    return <div className="container-fluid my-3">
      { cardsElements }
    </div>
  }
}

export default CardViewer;

2 Answers 2

3

Create an instance in this way:

const instance = Axios.create({
    baseURL: 'http://localhost:3000',
});

And then use it however you want:

instance.get('/cards').then(response => {/* response processing */})

Here you can learn more about creating an instance.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I thought that parameter is baseUrl instead baseURL, thanks
1

Hi you can try create the instance using this piece of code

const callWebService = (options) => {
    const axiosInstance = axios.create({
        baseURL: config.serverURL,
        withCredentials: true,
        timeout: 1000 * 10
    });
    return axiosInstance(options);
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.