0

I'm building a dashboard that will pull in data via an HTTP request. In order to get the data, I have to include date based "start" and "end" search params in the URL, so I decided to use URLSearchParams to allow this to be somewhat dynamic.

However, when I pass in the URLSearchParams into the final request they're getting altered. The basics layout of my code is as follows:

// create new date as of "today", and one week previous
const today = new Date()
const prevWeek = new Date(today.valueOf() - (86400000 * 7))

// get dates in UTC format for use in params
function getUTCDate(date) {
  const utcDay = date.toISOString()
  return utcDay
}

// creating params based on dates
const paramObj = {start: getUTCDate(prevWeek), end: getUTCDate(today)}
const params = new URLSearchParams(paramObj)

// setting up URL for HTTP call
const mailboxUrl = new URL(`https://api.helpscout.net/v2/reports/email?${params}`)
const config = {headers: {authorization: ""}}

If I log params I get URLSearchParams { 'start' => '2020-11-17T21:59:20.459Z', 'end' => '2020-11-10T21:59:20.459Z' } which has the correct formatting.

However when logging the final URL I get 'https://api.helpscout.net/v2/reports/email?start=2020-11-17T21%3A58%3A52.627Z&end=2020-11-10T21%3A58%3A52.627Z'

Basically the colons are getting replaced with ISO character codes... but I'm not exactly sure why that is. I'm receiving a 400 error when making this request, so that's really the issue that I'm trying to resolve

  • `URLSearchParams` uses [URL encoding](https://en.wikipedia.org/wiki/Percent-encoding) when creating the query string. `:` is part of the _reserved character list_. This is not a problem – Phil Nov 17 '20 at 22:15
  • FYI, to create a date one week prior, I would use `const prevWeek = new Date(); prevWeek.setDate(prevWeek.getDate() - 7)`. There are not always 86400000ms in a day – Phil Nov 17 '20 at 22:19
  • Thanks Phil, so basically you're saying that conversion shouldn't be contributing to any bad request errors? – Vincent Levinger Nov 17 '20 at 22:20
  • That's correct. When the query parameters are read by the other site, the values will be interpreted correctly – Phil Nov 17 '20 at 22:22
  • Ah, got it Phil, really appreciate it! Looks like the API wants those millisecond values trimmed off which is what's causing the 400 error – Vincent Levinger Nov 17 '20 at 22:31
  • That's pretty bad if their code can't parse valid ISO 8601 strings – Phil Nov 17 '20 at 22:33
  • Yea it's a bit odd... in their documentation they request ISO 8601 strings, but their formatting doesn't include the ```sss``` value https://developer.helpscout.com/mailbox-api/overview/errors/#IsoDateTime – Vincent Levinger Nov 17 '20 at 22:35

1 Answers1

0

ISO character replacement wasn't the issue. The API I'm using wants the millisecond value trimmed off, which is what was causing the bad request