JacobSiegel JacobSiegel - 23 days ago 9
Javascript Question

Formatting String For Network Request (JavaScript)

Here is my dilemma:
I need to format the body of my POST request exactly like the example below, and the quotation marks are very important.

'{"url":"https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg"}'


Although, I would eventually like to pass a value into the url instead of having it hardcoded in.

I have tried using:

const uriInQuotes = "'"+uri+"'";
'{"url":+uriInQuotes+}'


But the format is still not correct. Anyway I can go about doing this? With the quotation marks properly formatted?

Thanks for the help in advance.

Answer

Just use JSON.stringify() to convert your object to a valid JSON string which is what it looks you need to POST.

let requestBody = { url: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg' };

return JSON.stringify(requestBody);