I am trying to do a post request to get a token that will let me have access to an access token. Whenever I try to post to it I get an error that the access_token property can't read something that is undefined. I am pretty sure this means that my post request isn't working and I don't know why. I think it has something to do with my post parameters and the map and subscribe methods. I just don't know how to fix them. Any help would be appreciated, thanks.
This is my code for the post request.
httpPostRequest() {
this.grabState();
this.grabCode();
this.grabSessionStorage();
this.grabTokenUri();
this.grabClientId();
this.grabSecret();
this.grabServiceUri();
this.grabRedirectUri();
this.data = {
code: this.code,
grant_type: 'authorization_code',
redirect_uri: this.redirectUri,
};
const headers = new Headers({'Accept': 'application/json'});
const options = new RequestOptions({ headers: headers });
return this._http.post(this.tokenUri, this.data, options)
.map((postResponse: Response) => postResponse.json())
.subscribe(resPostResponse => (this.postResponseJson = resPostResponse));
}
Angular HttpClient is asynchronous, so you have to subscribe to your post request (in your view for example).It's now returning undefined because it's not executed yet. You can use a callback to execute an another function after getting the token.
Related
I am trying to replay a request to another instance of my API, so I am making a POST request as shown below. This works fine except for the fact that the data (JSON.stringify(req.body)) is not being passed. req.body on the other instance returns a blank map {} even though I have confirmed that JSON.stringify(req.body) returns what I expect. Is there something wrong with how I am passing the data with the POST request? Thanks in advance for any help.
var betaReq = https.request({
hostname: 'some-product-beta.cloudfunctions.net',
path: '/intercomEventsReplayed',
method: 'POST',
headers: {
'x-hub-signature': req.headers['x-hub-signature']
}
});
betaReq.write(JSON.stringify(req.body));
betaReq.end();
I created a JavaScript Bot using BotFramework and Botbuilder-js.
For this bot I use an adaptive dialog.
At some point in the dialog I need to send an HTTP-request.
For now, my HTTP-request Step looks like this:
new HttpRequest().configure({
resultProperty: new StringExpression("user.teamProfile.accessToken"),
url: new StringExpression('https://login.microsoftonline.com/myTenantId/oauth2/v2.0/token'),
method: HttpMethod.POST,
contentType: new StringExpression('application/x-www-form-urlencoded'),
headers: {
"Content-Type": new StringExpression("application/x-www-form-urlencoded")
},
body: new StringExpression("client_id: myClientId, scope: https://graph.microsoft.com/.default, client_secret: myclientSecret, grant_type: client_credentials"),
responseType: ResponsesTypes.Json
})
The bot in itself is working but when it tries to execute the HTTP-Request step, I get the following error message:
Error: TypeError: path.indexOf is not a function
Unfortunately, I don't get any more information. Can anyone help me ?
Best regards,
BufferOverflow
Since the HttpRequest-Step didn't work, I changed to a CodeAction.
Inside this CodeAction I then do my Http-Requests and work on the results (transforming them or saving them in a dialog variable).
A Code Snippet could look like the following:
new CodeAction(async (dc, options) => {
// Send your request
// options being the headers, body, etc.
const response = await this.fetch(url, options);
// Work on you result and if necessary, save it to a dialog variable
dc.state.setValue("user.yourPropertyName", value);
// Needed for the Bot to continue working
return await dc.endDialog();
})
I am trying to implement Discord OAuth2 in my node.js Application. As soon as I try to get the access token from the given authorization code, I always get the HTTP response Error 400 {"error": "invalid_grant"}
let xhr = new XMLHttpRequest()
xhr.open('POST', 'https://discord.com/api/oauth2/token')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
let payload ={
client_id: clientID,
client_secret: clientSecret,
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUrl,
scope: 'identify'
};
console.log(payload)
xhr.send(JSON.stringify(payload))
xhr.onreadystatechange = () => {
console.log(xhr.status)
console.log(xhr.responseText)
}
xhr.onerror = () => {
console.log('Failed')
}
Okay I solved the issue. For everyone who is experiencing the same issue that I had, I solved it by using axios and querystring to send the POST request to the Discord API (https://github.com/discord/discord-api-docs/issues/1131)
It seems that there is a problem with the JSON and the x-www-form-urlencoded format.
payload should not be a js object but a form data i.e
let payload = new FormData();
payload.append("key in string","value in string")
I had the same issue when trying to use on Next.js's GetServerSideProps function.
After searching a lot, I found an closed issue on Github solving this problem
(Github Issue: Deep Linking with OAuth2 Not Working). Basically, we could not use JSON object on authentication request's body. We must use URLSearchParams object instead.
The payload should look like:
const payload = new URLSearchParams()
payload.append('client_id', process.env.DISCORD_CLIENT_ID)
payload.append('client_secret', process.env.DISCORD_CLIENT_SECRET)
payload.append('grant_type', 'authorization_code')
payload.append('redirect_uri', process.env.DISCORD_REDIRECT_URI)
payload.append('code', accessCode)
payload.append('scope', 'identify')
In my case, it was a very silly error.
Instead of "response_type", I sent "response_type " (with a space); I randomly realized when I printed the HTML-formatted string and saw a %20 😂
Make sure the parameters have the correct names!
I'm trying to get an OAuth token for the Reddit API following the Application Only OAuth instructions. My reddit app is an installed app, so for my grant_type I'm using https://oauth.reddit.com/grants/installed_client.
Currently I'm running a very short JS script to query the API and get a token:
const APP_ID = 'MY_APP_ID'
const DEVICE_ID = 'TRACKING_ID_20_TO_30_CHARS'
let form = new FormData()
form.append('grant_type', 'https://oauth.reddit.com/grants/installed_client')
form.append('device_id', DEVICE_ID)
fetch('https://www.reddit.com/api/v1/access_token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(`${APP_ID}:`)}`,
}),
body: form })
.then(handleResponse)
.then(function(data) {
console.log(data)
})
.catch(error => console.error(error))
function handleResponse(response) {
return response.json()
}
(Note: running the snippet as-is will give you a NetworkError because the APP_ID isn't a real one and I don't want to give mine out.)
The response I get is:
{
"error": "unsupported_grant_type"
}
When I try the same API request using a REST client I get back the expected response, so this makes me think that the problem is JavaScript-related. Since the grant_type matches what the instructions say I'm not really sure what to do with the error. I'm hoping someone else more experienced with OAuth will know what is going on here.
The problem was the use of the FormData object. In earlier stages of troubleshooting I found this answer on Reddit and decided to use it, but that didn't work for me.
It was submitting the data as multipart/form-data rather than application/x-www-form-urlencoded, which Reddit's OAuth server did not like. I wrote a helper function based on this answer which did the trick:
function urlEncode(data) {
let out = [];
for (let key in data) {
out.push(`${key}=${encodeURIComponent(data[key])}`);
}
return out.join('&')
}
I want to send some post data to an api
10.11.12.13/new/request/create
this is an API to create a new request in portal. now I am making one application in NodeJs and want to create request from node js application.
now I have to send in this format
{"user":"demo", "last_name":"test","contact":"989898989"}
so how can I send data on above url to create a new request.
I am a beginner in NodeJs and don't have much idea.
any help will be appreciated.
Thanks in advance
I would recommend to use axios or any other request lib :
const axios = require('axios');
axios.post('10.11.12.13/new/request/create', {
user: 'demo',
last_name: 'test',
contact: '989898989',
});
here is an example using request module
var headers = {
'Content-Type': 'application/json'
}
var options = {
url: "10.11.12.13/new/request/create" ,
method: 'POST',
headers: headers,
json: true,
body: {user:"demo", last_name:"test",contact:"989898989"}
}
request(options, function (error, response, body) {
if (error) {
//do something
}
console.log(body)//do something with response
})
You can use postman REST client for GET method using your URL and Body (which you want to post) and click on * Code * and select NodeJS and their you will find code generated for you to work with. Here is the link https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets
With my experience, it is good to start with Request package for node js. Here is the link for your reference: https://www.npmjs.com/package/request