0

I want to call a REST API from JavaScript.

Here's what I've tried:

var mainURI = '<MyAPIURI>';
var mainURIEncoded = encodeURI(mainURI);

var mainRequest = new XMLHttpRequest()
mainRequest.open('GET', mainURIEncoded, true)

mainRequest.onload = function () {
    var data = JSON.parse(this.response)
}

I get this error:

No HTTP resource was found that matches the request URI 'MyAPIURI(Cut off at '#')'

My URI has a '#' symbol in it and it seems like the problem is my mainURIEncoded string is cut off at the '#'.

Any help appreciated.

Shiasu-sama
  • 1,179
  • 2
  • 12
  • 39
  • 1
    Have you tried figuring out what the ascii encoding for it might be like how space is `&nbsp`? – Mike Tung Mar 27 '19 at 13:01
  • 2
    `encodeURI()` does not alter the `#` character. – Pointy Mar 27 '19 at 13:01
  • 5
    the hash is not sent to the server. it is only a client side representation. – Daniel A. White Mar 27 '19 at 13:02
  • Seems like a good ole' case of a 404. Sure your URL is good? – Chris Neve Mar 27 '19 at 13:03
  • @Chris Neve Yes I'm sure. I don't know the encoding for '#' and I couldn't find a straight up easy google answer. – Shiasu-sama Mar 27 '19 at 13:05
  • 3
    Possible duplicate of [Why is the hash part of the URL not available on the server side?](https://stackoverflow.com/questions/3664257/why-is-the-hash-part-of-the-url-not-available-on-the-server-side) – Cid Mar 27 '19 at 13:06
  • I've debugged it and in the error displayed it definitely cuts off at the '#'. – Shiasu-sama Mar 27 '19 at 13:06
  • 3
    Generally, you should not `encodeURI()` the entire URL. You should use `encodeURIComponent()` to encode parameter values. In your case, assuming your URL is "http://myhost/api/action?action=#someParam", it's only the `#someParam` action that needs to be encoded. Show your actual URL so we can provide more info. – haim770 Mar 27 '19 at 13:06
  • @Cid I've replaced all '#' with %23 and now it works :D. – Shiasu-sama Mar 27 '19 at 13:09
  • Why didn't the encodeURI() change my '#' to '%23'? – Shiasu-sama Mar 27 '19 at 13:10
  • 2
    In URI syntax, the `#` marks the beginning of a fragment that should *not* be sent to the server. It's handled by the browser. If you want the `#` to be part of something sent to the server, you have to encode the URI piece-by-piece with `encodeURIComponent()`. – Pointy Mar 27 '19 at 13:11

1 Answers1

0

My solution was to replace all '#' with '%23' after using encodeURI() and encodeURIComponent().

Refer to the helpful comments on the question.

Shiasu-sama
  • 1,179
  • 2
  • 12
  • 39