Encode a string for sending with HTTP request?
Asked Answered
E

3

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?

Engaging answered 24/2, 2011 at 2:57 Comment(0)
I
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"'
});
Install answered 24/2, 2011 at 3:0 Comment(4)
Perhaps you could try: ?key="me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-" + encodeURIComponent("#a6e6f"); ?Bouncer
Kevin Gurney: Actually that worked great! What is the difference between encodeURI and encodeURIComponent?Engaging
Just read about an explanation: #76480 :) You should put your comment as an answer so I can make it to the accepted one.Engaging
Maybe it's just me but I think it's a fragile solution to selectively encode only a part of your query parameter...Install
A
1

urlencode it.

in Javascript: escape(string)

Alfredoalfresco answered 24/2, 2011 at 3:2 Comment(1)
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.Ban
S
0

Use encodeURIComponent as Husky mentioned in his comment.

?key=encodeURIComponent(https://me.yahoo.com/a/xt4hQ7QYssA8hymJKv8MeVQQKGhq_1jwvas-#a6e6f)
Susurrous answered 9/6, 2019 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.