I am using mithril.js in frontend application and backend application is running on ipv6 environment.
Calling post ajax request to backend using mithril.js.
async post(url, body = {}) {
return new Promise((resolve, reject) => {
m.request({method: 'POST', url, body}).then((data) => {
resolve(data);
}).catch((err) => {
reject(err.message);
});
});
}
Backed url is like this: http://[340f:c0e0:1d1:5gc0:g4fs:2::]:22923/backend.
But getting this error Template parameter names *must* be separated
while calling backend api.
Explanation of the error
Based on the documentation of
m.request()
, you can specify dynamic URLs:Since your backend URL contains colons, it's interpreted as being a dynamic URL.
According to the documentation of
m.buildPathname()
,m.request()
usesm.buildPathname()
internally to process dynamic URLs.The beginning of
m.buildPathname()
contains the following check regarding parameters of a path template (dynamic URL = path template populated with path parameters):(Source: https://github.com/MithrilJS/mithril.js/blob/v2.0.4/mithril.js#L1288-L1292)
And, again, since your backend URL contains colons, this is where you are getting the error. (You can verify this by trying to run
m.buildPathname('http://[340f:c0e0:1d1:5gc0:g4fs:2::]:22923/backend')
– you'll get the same error.)How to fix it
Since you can't get away from that regex check at the beginning of
m.buildPathname()
, your best bet might be to use a dynamic URL. Like so:Or when applied to your code:
Or alternatively you can specify the (dynamic) URL as the first argument of
m.request()
:Notice that there are three dots after the path parameter
:url
. Otherwise its value would be escaped/encoded. This is mentioned in the documentation of path handling. Example:Handling URL parameters
As mentioned in the other answer, if the URL contains parameters, the question mark will be duplicated:
One way to solve that would be to include the parameters in the path template:
However, if there are colons in the URL parameters, there's a possibility that you'll get the same error as originally ("Template parameter names *must* be separated").
There might be a way to solve this, but the previous code sample is already quite complex for this relatively simple use case. Which leads us to:
Alternative solution: don't use
m.request()
m.request()
is just "a thin wrapper aroundXMLHttpRequest
." It "returns a promise and triggers a redraw upon completion of its promise chain."If
m.request()
is difficult to work with due to using IPv6 URLs (or for other reasons), it can be easier to use something else for doing XHR requests. You could for example usefetch()
– just remember to callm.redraw()
at the end (m.request()
does this automatically).Sure,
m.request()
does more than just callsm.redraw()
at the end (see the docs), but it's also okay to use something else.