Due to a site cross-issue on Safari reason regarding CORS, I cannot use URL directly to frontend
what I am doing is making an API call to the URL and converting it to base64 sending to frontend and using it there passing in
Unfortunately, It's not working as the image shows is broken, I suspect that it's due to some unknown reason.
https://scontent.cdninstagram.com/v/t51.29350-15/325642177_505094921747710_9035707955179438711_n.webp?stp=dst-jpg&_nc_cat=107&ccb=1-7&_nc_sid=8ae9d6&_nc_ohc=hcMVLqiH044AX_O3sip&_nc_ht=scontent.cdninstagram.com&edm=AEoDcc0EAAAA&oh=00_AfDfXVcdc658NDViC2RvQDUbeZuvOhOl5M-xliFO9XfbdQ&oe=63C5998C
this is the image URL I am making API call
const config = {
method: "get",
url,
responseType: "arraybuffer",
headers: {},
};
const datares = await axios(config);
let base64;
base64 = Buffer.from(datares?.data).toString('base64');
if (datares?.status !== 200) {
return res.status(500).json({
success: false,
msg: datares?.data?.message || "Internal server error",
});
}
// base64 with img according to the url
const accpbase64 = `data:image/jpeg;base64,${base64}`;
res.status(200).json({
success: true,
data: accpbase64,
msg: "base64 retrieved successfully",
});
This is the API call response and below is the header of response
{
'x-storage-error-category': 'dfs:none;hs_p:200:HS_ESUCCESS',
'last-modified': 'Fri, 13 Jan 2023 14:04:31 GMT',
'x-haystack-needlechecksum': '2479215415',
'x-needle-checksum': '3312581816',
'content-type': 'image/jpeg',
'content-digest': 'adler32=3360421242',
'timing-allow-origin': '*',
'cross-origin-resource-policy': 'cross-origin',
'access-control-allow-origin': '*',
'cache-control': 'max-age=1209600, no-transform',
'accept-ranges': 'bytes',
'x-fb-trip-id': '2141700578',
date: 'Fri, 13 Jan 2023 17:46:19 GMT',
'alt-svc': 'h3=":443"; ma=86400',
connection: 'close',
'content-length': '112923'
}
https://codesandbox.io/s/unruffled-farrell-3jb93m?file=/src/App.js
here's example response of base64 using as in tag
Can someone help me here with this?
Your value in accpbase64 works fine. You just need to use that value in the src of your image.
See demo with base64 of image you provided, https://codesandbox.io/s/determined-noyce-u0j0g1
Related
Here is a sample POST request which I run inside the Console window of Chrome.
fetch("https://demo.wpjobboard.net/wp-login.php", {
"headers": {
"Host": "demo.wpjobboard.net:443",
"Content-Length": "19",
"Cookie": "wpjb_transient_id=1607759726-1847; wordpress_test_cookie=WP+Cookie+check",
"Content-Type": "application/x-www-form-urlencoded"
},
"body": "log=7887&pwd=789789",
"method": "POST",
}).then(console.log);
I need to navigate and see HTML rendered results inside the chrome, not just seeing some complex results inside the console. How to achieve this?
Fetch returns promise and first what you get is streaming data from your server. You need to convert it to text or JSON after that you can use it like a normal variable.
I have moved your URL and options in separate variables in order to focus code on fetch request implementation.
const url = `https://demo.wpjobboard.net/wp-login.php`
const opts = {
headers: {
'Cookie': `wpjb_transient_id=1607759726-1847; wordpress_test_cookie=WP+Cookie+check`,
'Content-Type': `application/x-www-form-urlencoded`
},
body: `log=7887&pwd=789789`,
method: `POST`,
}
fetch(url, opts)
.then(res => res.text()) // if you get json as response use: res.json()
.then(html => {
const win = window.open(``, `_blank`)
win.document.body.innerHTML = html
win.focus()
})
I'm requesting some data from an ODATA V2 service using the fetch api and want it to return in JSON format. That just works fine in Firefox and Chrome using the header accept: 'application/json; odata=verbose' but somehow MS Edge seems to ignore this header and returns xml instead.
The request itself has status 200 but I can't call respone.json() as it yields an error (but only in MS Edge).
Is there something else I need to add to the request or is it just a bug in MS Edge? I also tried to add $format=json to the url but with no appeal.
This is how the request is sent:
return fetch(window.location.origin + "/odata/v2/GraphService/Graph?$orderby=DATE desc", { headers: {
'Content-Type': 'application/json',
'Accept': 'application/json;odata=verbose'
}})
.then(response => {
if (response.ok) {
return response.json(); // this fails. response.text() works but yields xml
} else {
throw new Error('Request not ok');
}
})
.then(j => j.d.results.map(e => {
return {
ID: e.ID,
GRAPHNAME: e.GRAPHNAME
}
}))
.catch(err => console.log(err.message));
Edit: I actually noticed it's not xml that is returned but html containing a redirect link (I blurred the URLs):
<html><head><link rel="shortcut icon" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" /><script>document.cookie="fragmentAfterLogin="+encodeURIComponent(location.hash)+";path=/";document.cookie="locationAfterLogin="+encodeURIComponent(location.href.split('#')[0].split(location.host)[1])+";path=/";document.cookie="signature=...;path=/";location="https://<some-url>/oauth/authorize?response_type=code&client_id=<some-id>&redirect_uri=https%3A%2F%2F<some-other-url.com>%2Flogin%2Fcallback"</script></head></html>
I created an API in laravel and tested in postman and it is working perfect. But when I try it from angular it works fine for returning a string text but not for JSON response
I searched it on internet and found setting content-type:application/json and tried with different ways for setting content type in header but issue still persist
var obj = JSON.parse('{"email":"ab#gm.com","password":"12345678"}');
//1st type of header
var headers_object = new HttpHeaders().set('Content-Type',
'application/json');
const httpOptions = {
headers: headers_object
};
//2nd type of header
var HTTPOptions = {
headers: new HttpHeaders({
'Accept':'application/json',
'Content-Type': 'application/json'
}),
'responseType': 'application/json' as 'json'
}
return this.http.post<any>(`http://127.0.0.1:8000/api/auth/login`, obj,HTTPOptions ).subscribe(resp => {
console.log(resp);
});
Postman Output
browser network request/response
return this.http.post(http://127.0.0.1:8000/api/auth/login, obj,HTTPOptions ).map((resp: Response) => resp.json())
hopefully this will work
Basically, you are sending "string JSON" instead JSON Object, send Javascript Object directly instead of string will solve your issue,
Use the below-mentioned way to post JSON data to the server,
var httpOptions = {
headers: new HttpHeaders({
'Accept':'application/json',
'Content-Type': 'application/json'
})
};
var dataToPost = {"email":"ab#gm.com","password":"12345678"};
this.http.post('http://127.0.0.1:8000/api/auth/login', dataToPost, httpOptions)
.subscribe(resp => {
console.log(resp);
});
It was due to CORB.
Cross-Origin Read Blocking (CORB) is an algorithm that can identify
and block dubious cross-origin resource loads in web browsers before
they reach the web page. CORB reduces the risk of leaking sensitive
data by keeping it further from cross-origin web pages.
https://www.chromestatus.com/feature/5629709824032768
Solution run chrome in disabled web security mode.
This worked for me https://stackoverflow.com/a/42086521/6687186
Win+R and paste
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
This question already has answers here:
Encoding issue with requesting JSON from StackOverflow API
(2 answers)
Closed 5 years ago.
I have a particularly interesting issue, So I am trying to use Stackoverflow Search/Advanced API to query stackoverflow to get questions. I have tried it using PostMan and its returning JSON but in my Node.js application it is returning me raw data.
exports.GetQuestions = function(query,requestify)
{
var request = require("request");
var options = { method: 'GET',
url: 'https://api.stackexchange.com/2.2/search/advanced',
qs:
{ order: 'desc',
sort: 'activity',
site: 'stackoverflow',
q: 'Error: Can\'t find Python executable
"C:\\Users\\harig\\AppData\\Local\\Programs\\Python\\Python36\\python.EXE",
you can set the PYTHON env variable' },
headers:
{ 'postman-token': 'b0b78842-94cd-a0b9-39cc-0e099136900c',
'cache-control': 'no-cache',
'Accept': 'application/json' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
}`
I generated the code for the request using postman itself, I tried it on different API and the same code is working fine.
I need help in figuring out how to get JSON as response.
Here is the response:
cache-control: private
content-type: application/json; charset=utf-8
content-encoding: gzip
access-control-allow-origin: *
access-control-allow-methods: GET, POST
access-control-allow-credentials: false
x-content-type-options: nosniff
date: Sun, 21 Jan 2018 16:12:19 GMT
connection: close
content-length: 4780
Here is a sample of data returned:
���������U����"�z�f%��-??ӵm��N�|�f&��fે�n�.""��DX�Ƀ�P��J�(�p�U�Q�N47 �1�M�.�|]�t5agA��0�rc �g�3��}
+�Y�q/�pL��M�RƜGwt�B��ڍ�#���9(>s��ʀ6�#�w���e/��Mu�ʮ��9,�ML|
�s9�a���ߑW�r�[����ߗa�������a�~6��>ͦ����u�3���a�|P-�ᣖ�S'
�
�#v�D�PXM�i��ȹ��O�{2N�s��?
����ڝ���O_������/ ���ř��M3��w�ܾ����g"�� ���$�(%"�r#S�Px3��;?4^}��n�S�f7U[���g7�
a�cȩbҷ�Oq����X,8w�5Szp�P�y���rg�<�������m�;�u���|��aXJ��!��~X�bK�#�b5���,)W+����)������+n[cl()�����lC>
okoSHcY��c\�TW0ƊLM
��ݒ���oN9دhV���t��rj��
*�cPޝ�~l���E�́Ѳ�o3Dp�Eus侫��L��R�n��i�`+����DF���h $~377s=��W��xP��#�CAN�1�T�Ub0c$�e����S���&���B�}�~��Q�������m��m�������a�|���sL�Y;z8��T}�j~�]}���El�����]|��B�����*nt�^�,�����
k'
7�J�IO�i�d�m�4"�N���DZ��1䞦'�[�&�j���~�6�).G��v=��gn��x4�6nh�����V��o�)���^ಧ�2����['6����z� �#�/���J���j+vD�xƍ)N����qC[C���U��Z|�����vh���_��>�gd�9��v���.��i�U�zJ��,�*J��RBt�s��iӮo��f�^A3��$�"7�N��!�l�b,"��96�#�������C���.��a�52'a�v�U��9��v]�l�~kΎ��ԌG�藊<9�eN;]t��n�k?;cu� L�u}�t���q;৯��=�����Y��ZK������AL.�L
The response you received is gzip compressed as shown by content-encoding: gzip.
Set gzip:true in your options.
var options = { method: 'GET',
gzip: true,
url: 'https://api.stackexchange.com/2.2/search/advanced',
qs:
{ order: 'desc',
sort: 'activity',
site: 'stackoverflow',
q: 'Error: Can\'t find Python executable
"C:\\Users\\harig\\AppData\\Local\\Programs\\Python\\Python36\\python.EXE",
you can set the PYTHON env variable' },
headers:
{ 'postman-token': 'b0b78842-94cd-a0b9-39cc-0e099136900c',
'cache-control': 'no-cache',
'Accept': 'application/json' } };
I am using Parse Cloud Code to make a 'DELETE' HTTP Request to Delete Multiple Messages from Iron.io.
It is using exactly the same headers and url as 'GET' request to Get Message from the Queue:
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'OAuth ' + ironToken
},
The 'GET' request does work, whether I put method: 'GET' or not inside Parse.Cloud.httpRequest().
It does work even if I send some data as body: (which are ignored).
However, for a 'DELETE' request, I need to send body:
body: {
'ids': ['someMessageId']
}
And this requests fails with very unhelpful message:
{
"status":400,"headers":
{"Access-Control-Allow-Origin":"*",
"Connection":"keep-alive",
"Content-Length":"32",
"Content-Type":"application/json",
"Date":"Tue, 06 May 2014 10:15:27 GMT"
},
"text":"{\"msg\":\"Failed to decode JSON.\"}",
"data":{"msg":"Failed to decode JSON."},
"buffer":[ ...],
"cookies":{}
}
Any idea why this happens and what else can I test?
body: {
'ids': ['someMessageId']
}
Is not valid json object. You need double quotes everywhere:
"body": {
"ids": ["someMessageId"]
}