How can I leave the dynamic baseURL in React

Asked

Viewed 550 times

-3

Hey, guys, what’s up? I have a question and would like help, I am using React to make a web page where any user can use it to consume Apis. To do this I am using the Tips, my question is the following, the idea of the page is the user use the input to enter the address of the API he wants to consume by clicking send the data is returned to him. However after searching a lot I only found the tutorials with the Axios baseURL with fixed addresses, I do not know how to recover the state of what the user typed and make the request to him, IE, leave the dynamic baseURL. Below is my code and the page, I thank you.

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

export class Home extends Component {
 static displayName = Home.name;
 constructor() {
    super()
    this.state = {
        url: '',
        result: '',
        method: 'post',
        token: '',
        body: '',
    };
}

UrlFunction = (eventUrl) => { this.setState({ url: eventUrl.target.value }) }
MethodFunction = (eventMethod) => { this.setState({ method: eventMethod.target.value }) }
TokenFunction = (eventToken) => { this.setState({ token: eventToken.target.value }) }
JsonFunction = (eventBody) => { this.setState({ body: eventBody.target.value }) }

async componentDidMount() {
    const response = await (await axios.get(this.state.url)).data
    const result = JSON.stringify(response, undefined, 4)
    console.log(result)
    this.setState({ result })
}

render() {
    const { result } = this.state;
    return (
        <div>
            <form onSubmit={this.componentDidMount} >
                <select value={this.state.method} onChange={this.MethodFunction}>
                    <option value="get">GET</option>
                    <option value="post">POST</option>
                    <option value="patch">PATCH</option>
                    <option value="put">PUT</option>
                    <option value="delete">DELETE</option>
                </select>
                <label>
                    URL
            <input type="text" name="url" value={this.state.url} onChange={this.UrlFunction} />
                </label>

                <label>
                    Token : Bearer
            <input type="text" name="token" value={this.state.token} onChange={this.TokenFunction} />
                </label>

                <button type="submit">Enviar</button>
            </form>

            <textarea value={this.state.body} onChange={this.JsonFunction} cols="75" rows="20">

            </textarea>

            <textarea value={result} cols="75" rows="20" readOnly disabled></textarea>
        </div>
    );
  }
}

inserir a descrição da imagem aqui

  • I don’t get it, because you’re already saving a new state to url? I don’t get it at all

  • in the above state I left the url started just to demonstrate it, the idea is to leave it empty for the user to fill in.

2 answers

1

To change the baseURL it is necessary to create a new instance of Axios with .create. Follow an example below:

// config/axios.js
let axiosApiServer = axios.create({
  baseURL: 'http://localhost:5000', // baseURL inicial
  timeout: 15000,
});

export const getAxiosApiServer = (baseURL) => {
  if (baseURL && baseURL !== axiosApiServer.defaults.baseURL) {
    // Criamos uma nova instância apenas se foi passado uma nova baseURL
    // se ela for diferente da baseURL atual

    axiosAppServer = axios.create({
      baseURL: apiUrl,
      timeout: 15000, // Não esqueça de passar as outras opções
    });
  }

  return axiosAppServer;
};
// components/Component.js
import { getAxiosApiServer } from '../config/axios';
 
export const Component = () => {
  function fetch() {
    // Para realizar um GET, faça:
    const data = (await getAxiosApiServer().get('/endpoint')).data;
    
     // lembrando que você pode mudar a baseURL assim:
    const data = (await getAxiosApiServer('http://localhost:3000').get('/endpoint')).data;
  }
};

I use a similar function to change the baseURL and also of token (which is passed by headers), then it is possible to adapt it to any configuration of the axios.create.

1

The very one axios.create() is dynamic, does not need to create an exaggerated module of its own, an instance of the baseURL when the current URL does not contain the "protocol", that is when nay is the entire URL, in the methods axios.get, axios.post, etc..

Only the baseURL when one creates an instantiation, something like:

const instance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
});

Also in your current code that doesn’t exist, so you don’t have baseURL, then just pass the entire URL directly:

// Se for Node.js 10, se for os mais recentes use o "import"
const axios = require('axios');

axios.get('https://stackoverflow.com.br/').then(function () {
    console.log("success");
}).catch(function (error) {
    console.log('Error', error.message);
});

If you create an instance but pass the entire URL itself axios will understand that is not the baseURL:

// Se for Node.js 10, se for os mais recentes use o "import"
const axios = require('axios');

const axios = axios.create({
    baseURL: 'https://stackoverflow.com/',
    timeout: 16000
});

// Vai requisitar o https://www.google.com/, ignorando o baseURL
axios.get('https://www.google.com').then(function (response) {
    console.log('success', response.data);
}).catch(function (error) {
      console.log('Error', error.message);
});

// Vai requisitar o https://stackoverflow.com/users/1518921, "considerado" o baseURL
axios.get('users/1518921').then(function (response) {
    console.log("success", response.data);
}).catch(function (error) {
      console.log('Error', error.message);
});

Or using await:

// Vai requisitar o https://www.google.com/, ignorando o baseURL
try {
    let response = await axios.get('https://www.google.com');

    console.log('success', response.data);
} catch (ee) {
    console.log('Error', error.message);
}

// Vai requisitar o https://stackoverflow.com/users/1518921, "considerado" o baseURL
try {
    let response = await axios.get('users/1518921');

    console.log('success', response.data);
} catch (ee) {
    console.log('Error', error.message);
}

To summarize, if you didn’t use or even if you used an instance just pass the entire URL in:

const response = await (await axios.get(this.state.url)).data

Browser other questions tagged

You are not signed in. Login or sign up in order to post.