How to convert a URL to a string in Javascript - javascript

I have a component which uploads an image to Firebase and then receives the image url, which I then store in MongoDB. The problem is I need to store the url as a string. Unformatted, it gets inserted as an object. This is an example url:
https://firebasestorage.googleapis.com/.../sample.jpeg?alt=media&token=474da151-d6...
I use the JSON.stringify method to convert to a string, which then gives me
{"https://firebasestorage.googleapis.com/.../sample.jpeg?alt":"media","token":"474da151-d6..."}
Here, alt=media&token=... has been converted to alt":"media","token":"...
What is best way to return the whole url untouched as a string (without the leading and trailing curly braces as well)? I have used .replace() to remove the curly braces but is there a function/method I should be using to do the whole task simply?
EDIT: Here's some more code:
I pass the url: (it's still a string here according to the console.log)
console.log("url: ",url)
await axios.put(`/api/users/${id}`, url).then...
However, when we goto /api/users.. the req.body is now an object, and if I use json.stringify the 'alt=media&token=' gets changed
case 'PUT':
try {
console.log("req body: ",req.body) // OBJECT
const stringUrl = JSON.stringify(req.body) // SEE BELOW
"https://firebasestorage.googleapis.com/...?alt":"media","token":"..."}

Without Content-Type header specified, your put request treats your string as query parameters. That's why it get broken down into key-value pairs.(e.g. a=b&c=d becomes {a:b, c:d}) You can wrap the URL in a object and send the object in JSON.
await axios.put(`/api/users/${id}`, {url},{headers:{Content-Type:"applicatino/json"}}).then...
Now you will receive a JSON in the req.body, and the url property will be your URL.
P.S. A pure string is technically valid JSON and no need to be wrapped in an object, but not all server implementation accept this. It is safer to send an actual object.

Related

Can you use either JSON.stringify or URL format in JS fetch() 'body' field?

When using fetch(), I've seen people write the body field either as body: JSON.stringify(...) or as body: prop1=val1&prop2.... Are both equivalent?
For fetch, both are permitted. Per MDN, the body may be:
a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object. Note that a request using the GET or HEAD method cannot have a body.
In your case, assuming body: prop1=val1&prop2 is a typo and you meant body: 'prop1=val1&prop2', both methods are permitted, because both are putting strings into the body property, and strings (USVStrings) are permitted there.
Of course, you should also make sure the server you're sending the request should be able to parse it. (A server may only be expecting a query string parameter, or it may only be expecting JSON, or it may be able to parse both, or it may be able to parse neither)

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

JS: convert string into object

I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");

Query String generated by $.param() include square brackets for array

I have an object like this:
var queryObject= {
name: 'Shwetanka',
subjects: ['Mathematics', 'Physics', 'Computers'],
stream: 'science'
};
When I create query string with this using $.param(queryObject) I get this as query string:
name=Shwetanka&subjects%5B%5D=Mathematics&subjects%5B%5D=Physics&subjects%5B%5D=Computers&stream=science
Expected: name=Shwetanka&subjects=Mathematics&subjects=Physics&subjects=Computers&stream=science
How do avoid [] added by the method in the query string for params with same name. In the backend I'm using struts2 to read params.
I've found the solution. I just have to pass 'traditional=true' in $.param(queryObject, true). This generates the query string i want.
When we have fields with same name in a form and it is submitted via GET/POST, it is bound to be send as an array of params with the same name.
And the server would be expecting the values as such. So, Even if you somehow remove that [], it ceases to be an array, and the server will get only one value.
jQuery param method is designed, with the same thing in mind.
Check out examples in http://api.jquery.com/jQuery.param/.

AJAX Post missing variable

Im using an ajax call like so:
o.open("POST",q,true);
o.setRequestHeader("Content-type","application/x-www-form-urlencoded");
o.setRequestHeader("Content-length",p.length);
o.setRequestHeader("Connection","close");
Where q = the url and query string.
p = the query string only.
My query takes the form of: "/apps/nettrax/f/events_detail.php?get=1&ids="+multiple values added like this: 123~34567~567~678~etc
This all works if there are a few values, but large value strings fail - the variable ids does not pass (although get is passed)...
* Im not using jquery.
You're sending a POST request, but specifiying the parameters in GET via the URL. There's a limit on the size of URLs, so this won't work. You should be passing the parameters in the send() call, so that they are specified as POST data:
var parameters = "ids=" + encodeURIComponent(ids);
o.open("POST","events_detail.php",true);
o.setRequestHeader("Content-type","application/x-www-form-urlencoded");
o.setRequestHeader("Content-length",p.length);
o.setRequestHeader("Connection","close");
o.send(parameters);
I guess one this two things may be happening:
a) your url string is too long, so it's beeing truncated
b) your parameters are not encoded as the url needs to be, so the string "breaks" the url. if using php use a function like urlencode() or build your own one.

Categories

Resources