Why is the method - POST unable to cache?
subhradeepnag opened this issue · comments
const Axios = require('axios')
const { setupCache } = require('axios-cache-interceptor')
const cacheTTL = 15 * 1000 // 15 seconds
const axiosInstance = Axios.create()
const cacheOptions = {
interpretHeader: false,
ttl: cacheTTL,
methods: ['post']
}
const axios = setupCache(axiosInstance, cacheOptions)
async function callClient(options) {
const response = await axios(options)
return response
}
async function beforeCacheFunction(options) {
const start = Date.now();
const response1 = await callClient(options)
const end = Date.now();
const timeTaken = end - start;
console.log(timeTaken) // in miliseconds
console.log(response1.cached) //false
}
async function afterCacheFunction(options) {
setTimeout(async () => {
const start = Date.now();
const response2 = await callClient(options)
const end = Date.now();
const timeTaken = end - start;
console.log(timeTaken) // in miliseconds
console.log(response2.cached) //false
}, 2000)
}
beforeCacheFunction({
url: 'https://reqres.in/api/users',
data: {
"name": "morpheus",
"job": "leader"
},
method: 'POST'
})
afterCacheFunction({
url: 'https://reqres.in/api/users',
data: {
"name": "morpheus",
"job": "leader"
},
method: 'POST'
})
Have you used the debug logs?
Yes,
{
status: 201,
statusText: 'Created',
headers: AxiosHeaders {
date: 'Mon, 05 Jun 2023 17:37:05 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '84',
connection: 'close',
'x-powered-by': 'Express',
'access-control-allow-origin': '*',
etag: 'W/"54-gzRW5Ik95MsBYyYzuBbCZZN8fgA"',
via: '1.1 vegur',
'cf-cache-status': 'DYNAMIC',
'report-to': '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=W7xnVPY3pwF1mYDKa5Gp3FDfROoDewZ8mwyB86CrsVlVC0DfSbPJfVvq8ZZ4rd8VodWEoTrweTPQQW9nuwd13LZwVyuYnJ4t0gfOpXp9hMfIkFO%2BsPr6Bq3%2F8Q%3D%3D"}],"group":"cf-nel","max_age":604800}',
nel: '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}',
server: 'cloudflare',
'cf-ray': '7d2a2e777db02e4d-BOM'
},
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [ 'xhr', 'http' ],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function], Blob: null },
validateStatus: [Function (anonymous)],
headers: AxiosHeaders {
Accept: 'application/json, text/plain, /',
'Content-Type': 'application/json',
'cache-control': 'no-cache',
pragma: 'no-cache',
expires: '0',
'User-Agent': 'axios/1.4.0',
'Content-Length': '34',
'Accept-Encoding': 'gzip, compress, deflate, br'
},
cache: {
update: {},
ttl: 15000,
methods: [Array],
cachePredicate: [Object],
etag: true,
modifiedSince: false,
interpretHeader: true,
cacheTakeover: true,
staleIfError: true,
override: false,
hydrate: undefined
},
url: 'https://reqres.in/api/users',
data: '{"name":"morpheus","job":"leader"}',
method: 'post',
id: '195472757'
},
request: <ref *1> ClientRequest {
_events: [Object: null prototype] {
abort: [Function (anonymous)],
aborted: [Function (anonymous)],
connect: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)],
timeout: [Function (anonymous)],
prefinish: [Function: requestOnPrefinish]
},
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: false,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: false,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
secureConnecting: false,
_SNICallback: null,
servername: 'reqres.in',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 10,
connecting: false,
_hadError: false,
_parent: null,
_host: 'reqres.in',
_readableState: [ReadableState],
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [TLSWrap],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular *1],
[Symbol(res)]: [TLSWrap],
[Symbol(verified)]: true,
[Symbol(pendingSession)]: null,
[Symbol(async_id_symbol)]: 6,
[Symbol(kHandle)]: [TLSWrap],
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kCapture)]: false,
[Symbol(kSetNoDelay)]: false,
[Symbol(kSetKeepAlive)]: true,
[Symbol(kSetKeepAliveInitialDelay)]: 60,
[Symbol(kBytesRead)]: 0,
[Symbol(kBytesWritten)]: 0,
[Symbol(connect-options)]: [Object],
[Symbol(RequestTimeout)]: undefined
},
_header: 'POST /api/users HTTP/1.1\r\n' +
'Accept: application/json, text/plain, /\r\n' +
'Content-Type: application/json\r\n' +
'cache-control: no-cache\r\n' +
'pragma: no-cache\r\n' +
'expires: 0\r\n' +
'User-Agent: axios/1.4.0\r\n' +
'Content-Length: 34\r\n' +
'Accept-Encoding: gzip, compress, deflate, br\r\n' +
'Host: reqres.in\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: Agent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype],
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 1,
maxCachedSessions: 100,
_sessionCache: [Object],
[Symbol(kCapture)]: false
},
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
path: '/api/users',
_ended: true,
res: IncomingMessage {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 4,
_maxListeners: undefined,
socket: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
rawHeaders: [Array],
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 201,
statusMessage: 'Created',
client: [TLSSocket],
_consuming: false,
_dumped: false,
req: [Circular *1],
responseUrl: 'https://reqres.in/api/users',
redirects: [],
[Symbol(kCapture)]: false,
[Symbol(kHeaders)]: [Object],
[Symbol(kHeadersCount)]: 26,
[Symbol(kTrailers)]: null,
[Symbol(kTrailersCount)]: 0,
[Symbol(RequestTimeout)]: undefined
},
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'reqres.in',
protocol: 'https:',
_redirectable: Writable {
_writableState: [WritableState],
_events: [Object: null prototype],
_eventsCount: 3,
_maxListeners: undefined,
_options: [Object],
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 34,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: [Circular *1],
_currentUrl: 'https://reqres.in/api/users',
[Symbol(kCapture)]: false
},
[Symbol(kCapture)]: false,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype] {
accept: [Array],
'content-type': [Array],
'cache-control': [Array],
pragma: [Array],
expires: [Array],
'user-agent': [Array],
'content-length': [Array],
'accept-encoding': [Array],
host: [Array]
},
[Symbol(kUniqueHeaders)]: null
},
data: {
name: 'morpheus',
job: 'leader',
id: '790',
createdAt: '2023-06-05T17:37:05.406Z'
},
id: '195472757',
cached: false
}
I just saw cache-control is set to 'no-cache'. Is it because of that?
If yes, can we change that?
The above is not debug logs. Please read the documentation before submitting an issue.
That's your answer, the cache predicate rejects the response, that's why no caching are done. Your server is returning your post request with headers that explictly says to avoid cache. You can disable this behavior by turning off header interpreter.
I just saw cache-control is set to 'no-cache'. Is it because of that?
Yes.
If yes, can we change that?
That's a header sent from the server, you need to change it there if you have sufficient permissions to do so.
Sorry for reopening the thread again
That's your answer, the cache predicate rejects the response, that's why no caching are done. Your server is returning your post request with headers that explictly says to avoid cache. You can disable this behavior by turning off header interpreter.
I've already set interpretHeader: false
in cacheOptions
in the above code, Still it's not able to cache
Am I missing something?