How to retrieve parameters from response body - node.js

I am trying to set up Spotify authorization using Authorization Code Flow ( as from https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow ) and got stuck receiving the tokens from the Spotify server.
When I make the POST request, I log the response body and set two variables: access and refresh tokens. The response body indeed contains these tokens, the variables are, however, are undefined (see logs).
console.log("Response.body: ")
console.log(response.body);
var access_token = response.body['access_token'],
refresh_token = response.body['refresh_token'];
console.log("Access: " + access_token);
console.log("Refresh: " + refresh_token);
I've tried both body.access_token and response.body.access_token as well.
A 2019-09-03T09:13:03.184411Z Response.body:
A 2019-09-03T09:13:03.184575Z {"scope":"playlist-modify-private","access_token":"BQAjB5eurOdl3oM2j-8db4pKi-...","token_type":"Bearer","refresh_token":"AQDtEcfw…
A 2019-09-03T09:13:03.184607Z Access: undefined
A 2019-09-03T09:13:03.184618Z Refresh: undefined

Make sure to convert the body to a proper object before trying to access properties.
Try the following:
const body = JSON.parse(response.body);

Related

Set response header along with a string

I am trying to send the token in the headers of an HTTP request from backend to the frontend along with sending my own defined string. However, I am getting an issue. The token is being printed as null on the client-side. I don't know why:
Here's my code:
Node/Express
if (bcrypt.compareSync(passcode, results[0].password))
{
const token = jwt.sign({id: email}, secret, {expiresIn: 86400 });
console.log(token);
if(results[0].userrights == 'full')
{
res.setHeader('x-access-token', token);
res.send("Full Authorization");
}
//rest of the code
}
Angular
this.http.post('http://localhost:3000/api/login', form.value, {responseType: "text", observe:
'response'})
.subscribe(responseData => {
console.log(responseData);
console.log(responseData.headers.get('x-access-token')); //prints null on the console
I have searched quite a bit and found different examples which is making it very confusing. I don't want to use response status rather my own defined string. I have tried different things to print the variable but it still is throwing as null.
If you are using a browser extension to allow CORS requests then Access-Control-Expose-Headers should be added to the headers on server side. Please try adding the following line: res.setHeader('Access-Control-Expose-Headers', '*')
Angular2 's Http.post is not returning headers in the response of a POST method invocation
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

How to log the actual request header when using fetch API

Beginner question, I am using the fetch API in one of my Cloudflare Service Worker to send request to a third party; Everything works fine that I am able to send out the request and receive response; But now I have a need to log everything I sent and received, which I am not sure how exactly can I do so;
The main requirement:
Able to log the whole request header being sent
The problem is that the request header that I specified is not the full header being sent, like in the following example I only specified the content-type, but in real practice it will send with more properties added by the application itself, e.g. accept, x-forwarded-for, content-length, etc.
Request:
var toThirdPartyReqMethod = 'POST';
var toThirdPartyReqHeader = {'content-type': 'application/json'};
var toThirdPartyReqSetting = {
method: toThirdPartyReqMethod,
headers: toThirdPartyReqHeader,
body: toThirdPartyReqBodyArrayBuffer
};
var toThirdPartyUrl = "https://somewhere.com";
var fromThirdPartyResponse = await fetch(toThirdPartyUrl, toThirdPartyReqSetting)
var fromThirdPartyResponseBodyArrayBuffer = await fromThirdPartyResponse.arrayBuffer();
I am able to use fromThirdPartyResponse to digest the response; but I have no idea how to record the exact request I sent out.
I tried to do it as follows:
var oriReqHeaderContentType = fromThirdPartyResponse.request.headers.get("content-type");
But obviously it is not the right answer and returned with the following error:
TypeError: Cannot read property 'headers' of undefined
Anyone gets some idea of how to log the request being sent when using fetch API?
Sorry for asking beginner questions :(
You can access request headers like this
const contentType = req.get("Content-Type");

How to read Headers Parameter on server side "RESTLET"

[I am trying to send parameter with GET request on RESTLET Netsuite !!
but i am continuously facing issue 403 forbidden when i am trying to concatenate parameter with URL , without parameter Request is working good and getting response but i want to send parameter so now i am trying to send parameter through Header but not able to read on server side !! please help me out .how to read request header values/parameters on Netsuite RESTLET.
1-first i tried concatenate with +"&name=asd" and then Uri builder throws error 403 forbidden
2-Now i am sending parameters through request.header.add("name":"asd") working good
This is my client side request code in which i am attaching parameters in request header
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.ContentType = "application/json";
request.Method = "GET";
request.Headers.Add(header);
request.Headers.Add("email", "polutry#key-stone.co");
request.Headers.Add("password", "123-4567");
WebResponse response = request.GetResponse();///here i got 403 on concatination ////
function getCustomer(context)
{
var request =https.request.headers;///headers function not defined
// var email =request.email;
//var password = request.password;
}
Want to get header values on server side][1]
[1]: https://i.stack.imgur.com/SEB68.png
In RESTlet you don't have access to request-headers, instead you get all the arguments passed to RESTlet in scriptContext(function argument to RESTlet entry point, get in current case).
Check this out on how to use RESTlet and how you can pass arguments.
Note: Add { "Content-Type": "application/json" } header since you want to pass data to RESTlet.

Creating Stripe Express Connect Account, Getting 'unsupported_content_type' when POST to endpoint for account ID

Im having trouble sending "POST" request to stripes token endpoint at the end of creating connect express account. Currently, my application(ios) is opening the OAuth Link (which contains a redirect uri to my server(Firebase functions)) to the express account creation web page made by stripe. Once the user completes their account set up I receive the authorization code in the backend and then use the authorization code and client_secret_key to send a POST request to "https://connect.stripe.com/oauth/token". I'm using XMLHttpRequest npm to send a POST request within firebase functions and setting my parameters like this
var params = "client_secret=" + CLIENT_SECRET + "&code=" + AUTHORIZATION_CODE + "&grant_type=authorization_code"
and my request header like this
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
Yet I get back this error after sending POST request
"error": {
"type": "invalid_request_error",
"code": "unsupported_content_type",
"message": "Invalid request: unsupported Content-Type text/plain;charset=UTF-8. If error persists and you need assistance, please contact support#stripe.com."
}
I thought I was properly setting request header content-type to "application/x-www-form-urlencoded" but still getting back error as if the content-type was "Text/plain".
Here is full backend code
exports.CreateUsersPayoutAccount = functions.https.onRequest((req, res) =>{
const userID = req.query.state
const AUTHORIZATION_CODE = req.query.code
console.log(userID)
console.log(AUTHORIZATION_CODE)
//console.log(req);
var request = new XMLHttpRequest()
request.addEventListener('load', getStripeConnectUserID)
var params = "client_secret=" + CLIENT_SECRET + "&code=" + AUTHORIZATION_CODE + "&grant_type=authorization_code"
//var params = JSON.stringify({client_secret : CLIENT_SECRET, code : AUTHORIZATION_CODE, grant_type : "authorization_code"})
console.log(params);
request.open("POST", "https://connect.stripe.com/oauth/token", true)
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
//request.setRequestHeader("Content-length", params.length)
request.send(params)
})
If anyone could point me in the right direction it would be much appreciated, I am somewhat new to writing backend HTTP calls.
In the backend cloud function, rather than attempt to send the POST request from there, write the auth code to a spot in firebase database.
Back in Xcode have a listener function that executes if there's a change in that database spot. The function should then read the change (the auth code) and simply send an easy swifty POST request with Alamofire.
I understand why you made the uri direct to your specific cloud function (since its an http trigger), but isn't the point of sending a uri so that stripe can redirect the user back to a specific app page, does the user still get directed back to the app in your case???

how to parse" http GET request"'s text response in nodejs?

I make a HTTP GET request to Facebook to have a long live token , as a response I have a plain text with the access token and expiration date , but I don't know how to parse it.
request.get('https://graph.facebook.com/oauth/access_token?client_id=' + APP_ID + '&client_secret=' + APP_SECRET + '&grant_type=fb_exchange_token&fb_exchange_token=' + CURRENT_ACCESS_TOKEN)
.on('data', function(data) {
console.log("body= " + data);
});
res.render('SocialMedia.ejs');
I tried data.access_token but it's undefined
Go through this documentation to get working with the lates 2.8 API (recommended). This will return a JSON response.
If you want to continue using your API then to parse your response which is in the form of url query params -
access_token=(the token)&expires=5166486 // data
You can do this -
var qs = require('qs');
var response = qs.parse(data); // assuming data is as mentioned above
console.log(response); // will print {access_token: (the token), expires: 5166486}
Now you can access the token like this -
response.access_token;

Resources