0

I am on Javascript/Node.js and when I'm making a HTTP request with this query parameter:

?key="https://me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-#a6e6f"

I get an error because it shops of everything after:

?key="https://me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-

I wonder how I can encode this string so it doesn't chop it off?

generalhenry
  • 17,227
  • 4
  • 48
  • 63
ajsie
  • 77,632
  • 106
  • 276
  • 381

3 Answers3

8

I'm assuming that the hash (#) at the end of your URL is actually part of the query argument. The problem is that Node.js is treating it as the hash of your overall URL, which plays no role in HTTP requests. Thus, you'll need to properly encode the query string.

A structured API function like querystring.stringify is probably best.

var query = querystring.stringify({
  key: '"https://me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-#a6e6f"'
});
ide
  • 19,942
  • 5
  • 64
  • 106
  • 2
    Perhaps you could try: ?key="https://me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-" + encodeURIComponent("#a6e6f"); ? – Kevin Gurney Feb 24 '11 at 03:02
  • Kevin Gurney: Actually that worked great! What is the difference between encodeURI and encodeURIComponent? – ajsie Feb 24 '11 at 03:08
  • Just read about an explanation: http://stackoverflow.com/questions/75980/best-practice-escape-or-encodeuri-encodeuricomponent :) You should put your comment as an answer so I can make it to the accepted one. – ajsie Feb 24 '11 at 03:12
  • Maybe it's just me but I think it's a fragile solution to selectively encode only a part of your query parameter... – ide Feb 24 '11 at 03:16
1

urlencode it.

in Javascript: escape(string)

Chris Cherry
  • 28,118
  • 6
  • 68
  • 71
  • 3
    `escape` doesn't exist on NodeJS. In client-side Javascript it's deprecated because it doesn't work with non-ASCII characters. Use `encodeURI` and `encodeURIComponent` instead. – Husky Aug 24 '11 at 18:44
0

Use encodeURIComponent as Husky mentioned in his comment.

?key=encodeURIComponent(https://me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-#a6e6f)
yikekas
  • 129
  • 1
  • 5