Add extra headers to chrome.downloads.download api - google-chrome

I'm trying to add extra headers to the chrome.downloads.download method but I get always this error:
TypeError: Error in invocation of downloads.download(downloads.DownloadOptions options, optional function callback): Error at parameter 'options': Error at property 'headers': Error at index 0: Unexpected property: 'Authorization'.
I'm trying to use the authorization header. This is the code, how I can fix it?
browser.downloads.download({
url: `https://myapp.herokuapp.com/u/${response.data.processed_file}`,
saveAs: true,
method: 'GET',
headers: [{'Authorization': `Bearer ${this.$store.getters.userToken}`}]
}).then( (downloadId) => console.log('Download completed', downloadId) );

Related

Avoid 406 error when using GET method in API testing with Cypress

I would like to test the api of an application, I've got a token from the developer, but I'm getting an error 'cy.request() failed on:
https://******************************
The response we received from your web server was:
406: Not Acceptable
This was considered a failure because the status code was not 2xx or 3xx.'
This is the code that I used:
describe('API Test', () => {
const token = 'your_token_here';
it('Should make a GET request with a Bearer token and avoid 406 error', () => {
cy.request({
method: 'GET',
url: 'https://your-api.com/endpoint',
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json'
}
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.be.an('object');
});
});
});
I tried with 'Accept': 'application/json' and 'Content-Type': 'application/json', but it didn't help.
the Content-type header is used to indicate the original media type of the resource.
Here since you are sending a GET request content-type does not matter.
the Accept header is used by the sender of the request(browser) to specify response media types that are acceptable. So here in your case maybe the type of the response is not application/json that's why you are gettin an
406: Not Acceptable
I found also in this source that in some cases, the server could be responsible for the 406 Error since it's the network object producing the error. Perhaps the server is misconfigured and can't handle the request correctly. Maybe it's a traffic routing issue.
so try your REQUEST without any header and if the 406 still occurs you are sure that it is from ther server and that your REQUEST is OK.

How to fix: "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"

I'm working with React-Native right now, trying to pass formdata to a backend php-file as JSON. But everytime the form is submitted the console shows the following error "SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data". With firefox I checked the request and response under network.
Under request it shows the JSON correctly, under response it shows the JSON correctly. 1 thing that stands out is that under Headers, it says that response Content-Type is text/html and that request Content-Type is text/plain. Could that be causing the issue? I wouldn't know what else to do since I already specify the Content-Type in the code.
Google Chrome says .then(response => response.json()) is causing the error.
await fetch('http://192.168.2.16/React-Native/endpoint.php', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
body: JSON.stringify({
intensiteit: intensiteit,
soortStank: soort,
latitude: lat,
longitude: long,
buurt: neighbourhood,
}),
mode: 'no-cors',
})
.then(response => response.json())
.then(responseJson => {
Alert.alert(JSON.stringify(responseJson));
})
.catch(error => {
console.error(error);
});
The php-file:
$obj = file_get_contents('php://input');
$obj = json_decode($obj, true);
$result['soort'] = $obj['soortStank'];
echo json_encode($result);
And yes I looked at other posts, but they didn't help sadly. I also tried adding dataType: 'json', in there, but that didnt help.
The request from your front-end app to the back-end endpoint is a cross-origin request. Adding mode: 'no-cors' to the fetch request doesn't change this, so remove it to begin with.
Next, the php endpoint must include some header declarations to allow the cross-origin request to succeed.
Add the following to the top of the php file, replacing the http://localhost:9999 part with the origin you are sending the request from. When testing locally, it'll likely be identical apart from the port number. When running in production, be sure to replace it with the correct origin for your front-end app eg. https://www.example-app.com.
header("Allow-Access-Control-Origin: http://localhost:9999");
header('Content-Type: application/json');
This should work.
This is likely a problem of null values.
Replace null values with empty strings in the body.
Perhaps, you also just need to change the php file to:
$obj = file_get_contents('php://input');
$obj = json_decode($obj, true);
$result['soort'] = $obj['soortStank'] ?? '';
echo json_encode($result);

Capture the response of async axios call in react

async saveForm(data) {
return await axios({
method: "post",
url: FORM_PORTAL_CONTROLLER_URL + 'savemoratorium',
body: JSON.stringify(data)
}).then(res =>
this.setState({ refNo: res.data.reference }))
}
I cannot set set state which im getting from the request it gives me below error. The Post request executes perfectly. I want to capture the response and and change the state.function is inside a component. Following errors are in the console of the page and im getting a white page after this.
react_devtools_backend.js:6 TypeError: Cannot read property 'length' of undefined
react-dom.production.min.js:152 Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
Add a validation before render
// Sample 1
if(Array.isArray(refNo) && refNo.length){
//your code
}
//Sample 2
{Array.isArray(refNo) && refNo.length? customRenderFunction(): null}
I have found the root cause for this case. Its because I had a conflict with material ui node module. (makeEffect,useEffect)

JSON stringify not producing expected json

This is a question for anyone who has used Stripe.js. I am trying to build a payment system with express and node. I have been stuck on this problem for about a day. I just want to post a json object with {"token":"token_val","item":"item_val"}. I am so close to getting it done, but when I post the data to my payment route my json object is messed up. I am getting a json of the form {'{"token":"token_val","item":"item_val"}': ''}.
var stripeHandler = StripeCheckout.configure({
key: stripePublicKey,
locale: 'en',
token: function(token){
var cartItem = document.getElementById("Monthly").id;
var data = [{stripeTokenId: token.id, items: cartItem}];
fetch('/purchase', {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
// "Content-Type": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
})
}
})
Is there something wrong with this post that's causing the issue? I can't seem to understand why I'm getting this json obj key with a blank value.
I have tried two different content types, but nothing really seems to make a difference.
The problem was that I was not using express.json(). I added app.use(express.json()) to my app.js file and this fixed everything. I hope this helps someone.

JSON Parse error: Unrecognized token '?' in React Native

I am working on React Native project and I try to transform datas from a server to JSON.
I have already done it on other projects, so I know how it works, but this time I have an error :
"JSON Parse error: Unrecognized token '<' ".
Here is my code :
fetch('https://app.fr', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
})
.then((response) => response.json())
When I do response.text() instead, I get a string which is a correct JSON format. So I know the datas are not the problem.
fetch('https://app.fr', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
})
.then((response) => response.text())
After looking on forums, I found that the error could be that the server send me datas whith content-type "text/html" instead of "application/json". And yes, the server send me datas with content-type "text/html".
So I tried to change the content-type in the header:
fetch('https://app.fr', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
}),
})
.then((response) => response.json())
But I got that error : "JSON Parse error: Unrecognized token '?' "
So I thought it means that I need to change directly the content-type of datas on the server. But I can't do it because my client is using these datas for others projects.
Do yo know any possibility to transform to JSON datas with "text/html" content-type, without getting this kind of error?
Thanks !
I have found the problem !
In the datas client send to me, there was an invisible first character.
When I was rendering it on my phone I saw "{"message":"ok","testes":...} but when I log it in my console I saw that there was a strange character before the first "{".
I deleted it with response.text().substring(1) and it works !
Thanks for your answers !