1

I am making a random color generator. When I refresh or click the generate button, the api gets the same result. But when I refresh the api site, the information changes randomly.

Here is the api site and the demo

const BASE_URL = 'https://www.colr.org/json/colors/random'
const colorCardsTotal = '5'
function getColors(){
  axios.get(BASE_URL+'/'+colorCardsTotal)
  .then(function (response) {
    console.log(response.data.colors)
  })
  .catch(function (error) {
    // 2.handle error
    console.log(error)
  })
}

getColors()
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Penny Chang
  • 101
  • 8

1 Answers1

2

This won't refresh new colors due to browser disk cache.

enter image description here

To fix it, you need to add timestamp to your request:

const BASE_URL = 'https://www.colr.org/json/colors/random'
const colorCardsTotal = '5'

function getColors() {
  axios.get(BASE_URL + '/' + colorCardsTotal, {
      params: {
        t: new Date().getTime()
      }
    })
    .then(function(response) {
      console.log(response.data.colors)
    })
    .catch(function(error) {
      // 2.handle error
      console.log(error)
    })
}

getColors()

And here's the edited based on your demo.

Hoàng Huy Khánh
  • 1,071
  • 8
  • 16