So far I have this command to use in the terminal to make a GET request to readme.io api
curl https://dash.readme.io/api/v1 -X GET -u API_KEY:
PASSWORD VALUE is empty, the curl command works just fine in the terminal.
How do I do that with node.js
I have this.
const options = {
method: 'GET',
headers: {
'Authorization': 'Basic API_KEY:'
}
};
fetch('https://dash.readme.io/api/v1', options)
.then(res => res.text())
.then(body => console.log(body))
.catch(err => console.log('ERROR', err))
but it returns:
{"error":"Unauthorized","errors":null}
Can you please tell me what part did I mistaken?
Thanks in advance.
Related
In my node app, I'm trying to make a GET request to another server by Axios:
axios.get(`http://my-domain:2095/server/get-status`)
.then(result => { console.log(result.data) });
console.log shows me something like this (which is supposed to be JSON):
\x1F�\b\x00\x00\x00\x00\x00\x00\x03tα\x0E� \x14\x05�\x7F�3\x03/
��\f��8���\x12�\x04i\x17¿�j��g8\x15{Z%Ep�*��(9�\r<U�\x02\x06\r�x\x07���\��E0�^[OD�j��U�\x7F���r�)���mV�a�\x1D<�M�\x15R\x19���xc�\x04\x00\x00��\x03\x00\x02d&��\x00\x00\x00
The output is OK when I use ip:port in address. But not with domain:port.
Also The response of http://my-domain:2095/server/get-status is OK when I enter it in browser and Postman.
So what is the problem with Axios?
In axios v1.2.1, it fixed this error.
You need to add Accept-Encoding with application/json in axios.get header.
code in v 1.2.0
axios.get(`http://my-domain:2095/server/get-status`,
{
headers: {
'Accept-Encoding': 'application/json',
}
})
.then(result => { console.log(result.data) });
OR fixed in v1.2.1
axios.get(`http://my-domain:2095/server/get-status`)
.then(result => { console.log(result.data) })
I'm trying to implement a logout functionality with keycloaks which is running as a docker container.
When tried with postman I'm getting a 204 response, even after that I am able to access the web pages without having to login again (Hence logout has not happened correctly).
I have supplied the bearer token, client id, client secret and refresh token.
Please see the screenshots below from Postman.
Similarly have tried to implement these changes on nodejs using axios.But however things are not working.
var axios = require('axios');
var qs = require('qs');
var data = qs.stringify({
'client_id': 'VideoKYC',
'client_secret': 'my-clinet-secret',
'refresh_token': 'refresh token from cookies'
});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
var config = {
method: 'post',
url: 'https://3.109.1.86:8443/auth/realms/VideoKYC-Realm/protocol/openid-connect/logout',
headers: {
'Authorization': 'Bearer my-token',
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function (response) {
console.log("data is");
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Stack trace from where response is empty:
$ node logout.js
(node:16732) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
data is
""
Ideally I think we should get some response, and the token should be invalidated and automatically be logged out.
Please help me implement these changes
this code works for me.
const data = qs.stringify({
client_id: 'your_kc_clientId',
client_secret: 'your_kc_client_secret',
refresh_token: 'your_referesh_token',
});
const config = {
method: 'post',
url: `${process.env.KEYCLOAK_SERVER_URL}/realms/${process.env.KEYCLOAK_REALM}/protocol/openid-connect/logout`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then((response) => console.log('logout successfully'))
.catch((err) => console.log('error!!!'));
I get a JWT token after authenticating on an API with a POST req.
With that token, I can make a successful curl call from my command prompt:
curl --request GET https://corpURL/customer/wlsAccountManagement/v1/billingAccount/23435657 --header "env: it04" --header "Authorization: Bearer tokenstring..."
But when I try to exec this in node, it fails with Received HTTP code 503 from proxy after CONNECT.
I even tried a basic curl in the command prompt and it works:
curl -v https://corpURL/customer/wlsAccountManagement/v1/billingAccount/23435657
It just tells me I am unauthorized {"message":"Unauthorized"}, which is correct.
In node, I can't even get the {"message":"Unauthorized"}, it still gives me Received HTTP code 503 from proxy after CONNECT.
The reason I'm using curl is because I can see more info. Using axios it gives me a "socket hang up" error.
I have been trying to get this to work and searching online for a solution for over a day. Does anyone have any idea what's going on here? Why does it work in the command prompt but not in node? Thanks!
For anyone who can't get an exec with curl to work in node, or using the packages axios or request, use the https package in node like so:
const options = {
hostname: 'hostDomain', // no https protocol
port: 443,
path: '/path/to/get',
method: 'GET',
headers: {
Authorization: `Bearer tokenString`,
'Content-Type': 'application/json',
},
};
const req = https.request(options, response => {
response.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', e => {
console.error(e);
});
req.end();
This was the only way I was able to get the response so far, in node. I may tweak the structure as it doesn't seem that clean, but it works! You may also need to set the env var for your cert file NODE_EXTRA_CA_CERTS=cert.pem as I already had. Peace.
EDIT
I found a solution with axios, you need to create instances with a baseURL like the https request has it:
const axiosInstance = axios.create({
baseURL: 'https://corpURL',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
env: 'it04',
},
});
axiosInstance
.get('/get/path')
.then(response => console.log('response', response.data))
.catch(err => console.log('err', err));
I am trying to make a POST request to my graphql server that I have running on localhost:4000. To get my users I was using
getUsers(){
var query = `{users(id:""){username}}`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
})
})
.then(res => res.json())
.then(res => console.log('data returned', res))
this wasn't working so I made a curl request to see what was wrong,
curl -X POST http://localhost:4000/graphql -H "Content-Type: application/json "-d "{"query": "{users(id:""){username}}"
After I ran this I kept getting,
Unexpected token q in JSON at position
After looking up this issue on google first I found a tutorial that I thought might be able to help. Following the tutorial I changed my code to
getUsers(){
var query = `{users(id:""){username}}`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query,
})
})
//.then(r => r.json())
.then(res => res.text())
.then(text => console.log('data returned', text))
which still didn't log anything.
So i ran one last curl to attempt to solve this problem
curl -X POST http://localhost:4000/graph0ql -d "{"query": "{users(id:""){username}}"
which kept returning
{"errors":[{"message":"Must provide query string."}]}
Now I'm stuck and I don't know what to try next.
I checked the query string and it gives me the intended response in graphiql and the url is correct as well. My angular frontend server (from which I am making this request) is running on localhost:4200
Ok I feel pretty dumb. I didn’t call my function correctly. It works all that’s left is to actually use the data
The issue is how you're passing the query object. Try to update it into something like:
getUsers(){
var query = `query getUsers { users(id:"") { username } }`
fetch('http://localhost:4000/graphql', {
method:'POST',
headers: {
'Content-Type' :'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
})
})
//.then(r => r.json())
.then(res => res.text())
.then(text => console.log('data returned', text))
}
How can I convert this curl operation using request Node.js library:
curl -L -X GET -H "Content-Type:application/json" -H "Authorization: authorization..." -H "Scope: 11111111" https://url/download >> file.gz
/*the -L is curl option which means --location Follow redirects (H)
--location-trusted Like '--location', and send auth to other hosts (H)*/
If you just want to download to a file, you can use a head request type.
The request will look like so:
request.head({
url: "https://url/download",
followAllRedirects: true,
headers: {
'Content-Type': 'application/json',
'Authorization':'authorization...',
'Scope': '11111111'
}
}, (err, res, body) => {
request('https://url/download')
.pipe(fs.createWriteStream(`tmp/${res.path}`)).on('close', (data, err) => {
if(err) console.log(`Unable to write to file ${err}`)
console.log('Done')
})
})
I have used a similar snippet which worked well
Use Postmans code generator
Click code on the top left
Paste your curl request
Select Node.js Request from dropdown on top left of popup
You should then get JS snippet converted from your working cURL request
Here is the solution we have to put request inside another because: so the first request returns the url and the second one will download the file
const options = {
url: url,
headers: {
Authorization: `auth`,
'scope': profileId,
'content-type': 'application/json'
},
};
const r = request.get(options, async (err, res, body) => {
const fileStream = fs.createWriteStream(`${path}.gz`);
request(res.request.uri.href).pipe(fileStream);
// path exists unless there was an error
});