Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

394
Visualizações
Customizing Date Serialization in Axios

By default, when a JavaScript object contains a Date object, Axios serializes it into UTC. This means that the time transmitted is converted using the time zone. This doesn't work for my use case. I need to send the time without the time zone conversion to UTC.

I implemented a custom serializer based on #1548, but it has no effect. I have verified that the config is being modified, but when I look at the request payload, the dates are still using UTC (2022-02-03T04:59:00.000Z).

Note: My logic is more complicated, I am using toLocalString() in the code below to simplify the example.

const a = axios.create()
a.interceptors.request.use((config) => {
  config.paramsSerializer = (params) =>
    qs.stringify(params, {
      serializeDate: (date: Date) => date.toLocaleString(),
    })
  return config
})

Anyone understand why I can't override the default behavior and use my own date formatting?

Environment Axios Version 0.21.1

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's not Axios doing the serialisation. Date implements toJSON() which is employed when your objects (containing dates) are serialised via JSON.stringify()...

The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.

The paramSerializer is for serialising query params which is why it didn't apply to your request body.

To transform the request body, you want to use transformRequest.

Here's a generic, recursive transformer that finds dates and maps them to localised strings

import axios, { AxiosRequestTransformer } from "axios"

const dateTransformer: AxiosRequestTransformer = data => {
  if (data instanceof Date) {
    // do your specific formatting here
    return data.toLocaleString()
  }
  if (Array.isArray(data)) {
    return data.map(val => dateTransformer(val))
  }
  if (typeof data === "object" && data !== null) {
    return Object.fromEntries(Object.entries(data).map(([ key, val ]) =>
      [ key, dateTransformer(val) ]))
  }
  return data
}

You can then register this transformer in your Axios instance which will apply to all PUT, POST, PATCH and DELETE requests.

const instance = axios.create({
  transformRequest: [ dateTransformer ].concat(axios.defaults.transformRequest)
})

instance.post(url, data)

If the generic version seems a little heavy-handed, you can either transform the object yourself before posting...

const body = {
  date: new Date()
}

axios.post(url, {
  ...body,
  date: body.date.toLocaleString()
})

or register an inline transformer

axios.post(url, body, {
  transformRequest: [
    data => ({
      ...data,
      date: data.date.toLocaleString()
    }),
    ...axios.defaults.transformRequest
  ]
})
about 4 years ago · Juan Pablo Isaza Relatório

0

This is Phil's most excellent answer with small modifications for typescript. This is for axios 0.21.1. (In version 0.23.1+ it looks like AxiosTransformer was refactors to AxiosRequestTransformer)

const dateTransformer = (data: any): any => {
  if (data instanceof Date) {
    // do your specific formatting here
    return data.toLocaleString()
  }
  if (Array.isArray(data)) {
    return data.map(dateTransformer)
  }
  if (typeof data === 'object' && data !== null) {
    return Object.fromEntries(Object.entries(data).map(([key, value]) => [key, dateTransformer(value)]))
  }
  return data
}
const axiosInstance = axios.create({
  transformRequest: [dateTransformer, ...(axios.defaults.transformRequest as AxiosTransformer[])],
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda