Gzip decompression post request, axios, Node.JS - javascript

I'm doing a post request using axios in node.js.
The response is gzip data (behind, it's a huge json)
My goal is to read the json file behind the res (gzip).
Currently, my request is:
await axios({
method: "post",
url: process.env.API_URL + "/collection",
headers: {
"Content-Type": "application/json",
"Accept-Encoding": "gzip, deflate, br",
},
data: {
project: req.body.project,
platform: req.body.platform,
},
decompress: true,
}).then(async (response) => {
console.log(response.data);
});
But I receive data like:
�1�����Q��:GR}��"-��}$K�ևҹ\��°<ܖqw�Vmp�������Y!�����܋a�F�]� ���K%}0�rЈ^�<��/�>
��Q���C7��R>�]§.,j�rg�6�MUVH��_Xq�����}|��a����$����K��cˠ��[�vv�����o�6�v�?~�����h���'Kn.��e��ZUW�;���ŗ��Ӹ׿6j%��M������Էʫ�c1��A�����.�t8�����Ș,����_��C�����۬���?q$޽#�CFq...
Does someone have any suggestion?
Thanks !

In my case, I want to get the information of my accessToken (from Google provider), then I can send a GET request like this:
const googleOauth2Url = `https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${accessToken}`;
const { data } = await axios.get(googleOauth2Url, {
responseType: "arraybuffer",
decompress: true,
});
Then I receive the data that looks similar to yours. I investigate and find out that the data is compressed with gzip, then to use it we must decompress the data.
Now I use zlib.
zlib.gunzip(data, function (error, result) {
console.log(result.toString());
return result.toString();
});
And the final result is:
{
"issued_to": "some data,
"audience": "some data",
"user_id": "some id",
"scope": "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
"expires_in": 2971,
"email": "sample#gmail.com",
"verified_email": true,
"access_type": "offline"
}

Related

Getting an error for API request with javascript

I have an issue fetching the data from the local server. It was perfectly working and nothing changed. After some fetching, I started to receive an errors such as:
for POST request
Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON
and for GET request
unexpected token 's', \"server lau\"... is not valid json
The server side of the application is created with node js and run in localhost port 5000. It is a very simple "get" and "post" express methods.
And the frontend fetching method as next:
fetch("http://localhost:5000", options)
.then(res => res.json())
.then(res => console.log(res))
.catch((err) => console.log(err.message))
and the options as:
const optionPost= {
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": {
"string": "omurzak"
}
}
const optionGet= {
"method": "GET",
"headers": {
"Content-Type": "application/json"
}
}
Hope you understand the issue.
Thank you!

Fetch Post Request with Parameters is returning 400 status code?

I have a Post Request using fetch in react native, but I get a status code 400 for this, what is wrong with the code?
function sendRequest2() {
fetch(`https://sandbox-api.dexcom.com/v2/oauth2/token`, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: JSON.stringify({
code: "value1",
client_id: "value2",
client_secret: "value3",
redirect_uri: "http://www.google.com",
grant_type: "authorization_code",
}),
})
.then((response) => {
response.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => console.log("The error is: " + err));
}
Check your content-type, replace it by :
headers: {
"Content-Type": "application/json",
},
helpfull link : application/x-www-form-urlencoded or multipart/form-data?
You can try by removing JSON.stringify
That would solve the issue
Moreover you have shared a lot of open information regarding your server openly.
You must either hide it or add some dummy values. Sharing such a secure data openly is not recommended in open community.

Don't get expected result Node Fetch POST

I was trying to monitor my order packages
So there is the package track number.
Maybe it's not Submitting
I need to get the result from the expected page but it seems i'm on the base_url
code:
const fetch = require("node-fetch");
const base_url = "https://www2.correios.com.br/sistemas/rastreamento/";
const data = { acao: "track", objetos: "OD769124717BR", btnPesq: "Buscar" };
fetch(base_url, {
method: "POST",
body: JSON.stringify(data),
headers: {
acceptEncoding: "gzip, deflate, br",
connections: "keep-alive",
},
})
.then((results) => results.text())
.then(console.log);
the source of the form data:
acao=track&objetos=OD729124717BR&btnPesq=Buscar
Have you tried adding a catch to the fetch? If you do this, you will see that it is erroring with the error message "Failed to fetch". I've added this to your existing example so you can try for yourself:
const fetch = require("node-fetch");
const base_url = "https://www2.correios.com.br/sistemas/rastreamento/";
const data = { acao: "track", objetos: "OD769124717BR", btnPesq: "Buscar" };
fetch(base_url, {
method: "POST",
body: JSON.stringify(data),
headers: {
acceptEncoding: "gzip, deflate, br",
connections: "keep-alive",
},
})
.then((results) => results.text())
.then(console.log)
.catch(error => console.error("Error:", error.message));
I would recommend that you do some simple testing using cURL commands within the command line, or use a GUI tool such as Postman or SOAP UI to ensure that you have a valid URL and data parameters when testing this endpoint.

Sharepoint REST NodeJS A node of type 'EndOfInput' error

I'm using a NodeJS express server as middleware for an iOS app in order to store data in a Sharepoint list.
The iOS app makes a post request with the payload to a NodeJS server, which then authenticates up against Sharepoint 2013 and makes a POST request.
I'm assuming that authentication isn't an issues since I can read all items just fine. But when I try to create a new item in the list i get the following error:
"statusCode": 400,
"body": "{\"error\":{\"code\":\"-1, Microsoft.SharePoint.Client.InvalidClientQueryException\",\"message\":{\"lang\":\"en-US\",\"value\":\"A node of type 'EndOfInput' was read from the JSON reader when trying to read the start of an entry. A 'StartObject' node was expected.\"}}}"
My payload looks like this:
{
"__metadata": {
"type": "SP.Data.ResultsListItem"
},
"Vessel" : "TEST"
}
The post request inside my iOS app looks like this (angular.js):
item = {
"__metadata": {
"type": "SP.Data.ResultsListItem"
},
"Vessel" : $scope.selectedVessel.name,
};
$http({
method: 'POST',
url: $scope.selectedVessel.endpoint + "/post/survey",
data: JSON.stringify(item),
})
.then(function(response) {
console.log(response);
})
And finally the code inside the NodeJS server:
//Endpoint for posting results
app.post('/post/survey', function(req, res) {
//Get Sharepoint context
httpntlm.post({
url: siteurl + "/_api/contextinfo",
username: credentials.username,
password: credentials.password,
domain: credentials.domain,
headers: {
"Accept": "application/json;odata=verbose"
}
}, function(err, data) {
token = JSON.parse(data.body);
token = token.d.GetContextWebInformation.FormDigestValue;
createItem(token);
})
var postBody = req.body;
console.log(postBody);
var webUrl = "https://sp2016.xxx.com";
function createItem(token){
httpntlm.post({
url: webUrl + "/_api/lists/getbytitle('Results')/items",
username: credentials.username,
password: credentials.password,
domain: credentials.domain,
body: JSON.stringify(postBody),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": token,
"X-HTTP-Method": "POST",
"If-Match": "*"
}
}, function(err, data) {
if (err) console.log(err);
res.send("Done")
console.log(data)
});
}
})
Solution
So i found the issue. It seems the payload wasn't parsed properly. So i used body-parser package.
I then applied it on all routes:
var bodyParser = require("body-parser");
app.use(bodyParser.json());
This fixed it.

Getting access token with axios

I'm working with the Lyft API, and trying to figure out how to get an access token with axios with a node script.
I can manually get an access token by using Postman by filling out the form like this:
When I fill out the form, I can get a new token from Lyft successfully.
I'm trying to translate this into a POST request using axios by doing this:
var axios = require('axios');
var data = {
"grant_type": "client_credentials",
"scope": "public",
"client_id": "XXXXXXXXX",
"client_secret": "XXXXXXXX"
};
var url = "https://api.lyft.com/oauth/token";
return axios.post(url, data)
.then(function(response){
console.log(response.data)
})
.catch(function (error) {
console.log(error);
});
When I run the script, I get this error:
{ error_description: 'Unauthorized', error: 'invalid_client' }
What am I missing from my axios request? Any help would be appreciated!
According to the docs from Lyft (https://developer.lyft.com/docs/authentication), you need to use HTTP Basic auth.
var axios = require("axios");
axios.request({
url: "/oauth/token",
method: "post",
baseURL: "https://api.lyft.com/",
auth: {
username: "vaf7vX0LpsL5",
password: "pVEosNa5TuK2x7UBG_ZlONonDsgJc3L1"
},
data: {
"grant_type": "client_credentials",
"scope": "public"
}
}).then(function(res) {
console.log(res);
});
Happy coding :)
!IMPORTANT THING!
I strongly recommend you to change your secret_id and client_secret asap, because they are not the things to be public, if you use them for an important project or something like that.
I have solved my problem with this code.
var reqData = "grant_type=password&username=test&password=asd";
Axios({
method: 'post',
url: 'http://localhost:60439/token',
data: (reqData),
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}).then((response) =>{
console.log(response)
}).catch((error) =>{
console.log(error);
})
The Best solution was source using the following way. The client sends a POST request with following body parameters to the authorization server
grant_type with the value client_credentials
client_id with the the client’s ID
client_secret with the client’s secret
scope with a space-delimited list of requested scope permissions.
axios.post('https://exmaple.com/oauth/token',
'grant_type=client_credentials&scope=all&client_id=1&client_secret=bb'
)
.then(function(res) {
console.log(res);
})
.catch(error => {
console.log(error)
})
const axios = require("axios");
const qs = require("qs");
const url = "URL";
const data = {
grant_type: "client_credentials",
};
const auth = {
username: "Client ID",
password: "Client Secret",
};
const options = {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: qs.stringify(data),
auth: auth,
url,
};
axios(options)
.then((response) => {
console.log(response.data.access_token);
})
.catch((err) => {
console.log(err);
});
The following works. I got it by reading the above comments. The trick was the data field. To be clear use - data: "grant_type=client_credentials"
Example:
const axios = require("axios");
axios.request({
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
url: "/oauth2/token",
method: "post",
baseURL: "https://<ServerFQDN>/",
data: "grant_type=client_credentials",
auth: {
username: "<username>",
password: "<password>"
}
});

Categories

Resources