Reputation: 107
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;
Upvotes: 2
Views: 4943
Reputation: 484
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);
};
Upvotes: 1
Reputation: 3491
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.
Upvotes: 3