PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] Why api can't refresh?

 October 13, 2022     axios, javascript     No comments   

Issue

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>


Solution

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.



Answered By - Hoàng Huy Khánh
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing