I'm attempting to get the Salesforce Access Token using typescript and Axios. Unfortunately, I'm getting a Serialized Error. I can't figure out why. Can anyone assist me, please?
import axios from 'axios';
let clientId : string = ‘somestring-1’;
let clientSecret : string = ‘somestring02’;
let body = {
grant_type: "password",
client_id: clientId,
client_secret: clientSecret,
username: ’s’omeusername,
password: ‘somepassword_concatonated_with_secret’
}
let headers = {
"Authorization": `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
"Content-Type": 'application/x-www-form-urlencoded'
}
let data = await axios.post('https://test.salesforce.com/services/oauth2/token', body, {headers});
The results is
AxiosError: Request failed with status code 400
and
Serialized Error: Object {
"code": "ERR_BAD_REQUEST"
What on earth am I doing wrong?
Related
Hi I've been trying to do some sentiment analysis from google sheets. Here is my code:
function getSentiment(text) {
var apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var url = "https://language.googleapis.com/v1/documents:analyzeSentiment?key=" + apiKey;
var data = {
document: {
type: "PLAIN_TEXT",
content: text
}
};
var options = {
method: "post",
contentType: "application/json",
headers: {
"Authorization": "Bearer " + apiKey
},
payload: JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
return result.documentSentiment.score;
}
Here is what comes up:
Error
Exception: Request failed for https://language.googleapis.com returned code 401. Truncated server response: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response) (line 18).
I think the key is right (changed here for obvious reasons) and enabled so I'm not sure where I go from here. Any ideas? Thanks
I'm working through this tutorial on creating an app that uses the Spotify API. Everything was going great until I got to the callback portion of authenticating using the authentication code flow.
(I do have my callback URL registered in my Spotify app.)
As far as I can tell, my code matches the callback route that this tutorial and others use. Significantly, the http library is axios. Here's the callback method:
app.get("/callback", (req, res) => {
const code = req.query.code || null;
const usp = new URLSearchParams({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: "authorization_code",
});
axios({
method: "post",
url: "https://accounts.spotify.com/api/token",
data: usp,
headers: {
"content-type": "application/x-www-form-urlencoded",
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
},
})
.then(response => {
console.log(response.status); // logs 200
console.log(response.data); // logs encoded strings
if (response.status === 200) {
res.send(JSON.stringify(response.data))
} else {
res.send(response);
}
})
.catch((error) => {
res.send(error);
});
Though the response code is 200, here's a sample of what is getting returned in response.data: "\u001f�\b\u0000\u0000\u0000\u0000\u0000\u0000\u0003E�˒�0\u0000Ee�uS\u0015��\u000e�(\b\u0012h\u0005tC%\u0010\u0014T\u001e�����0��^:���p\u0014Ѻ\u000e��Is�7�:��\u0015l��ᑰ�g�����\u0"
It looks like it's encoded, but I don't know how (I tried base-64 unencoding) or why it isn't just coming back as regular JSON. This isn't just preventing me logging it to the console - I also can't access the fields I expect there to be in the response body, like access_token. Is there some argument I can pass to axios to say 'this should be json?'
Interestingly, if I use the npm 'request' package instead of axios, and pass the 'json: true' argument to it, I'm getting a valid token that I can print out and view as a regular old string. Below is code that works. But I'd really like to understand why my axios method doesn't.
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies[stateKey] : null;
res.clearCookie(stateKey);
const authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code',
},
headers: {
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64')}`,
},
json: true,
};
request.post(authOptions, function (error, response, body) {
if (!error && response.statusCode === 200) {
const access_token = body.access_token;
const refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { Authorization: 'Bearer ' + access_token },
json: true,
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect('/#' + querystring.stringify({
access_token: access_token,
refresh_token: refresh_token,
}));
} else {
res.redirect(`/#${querystring.stringify({ error: 'invalid_token' })}`);
}
});
});
You need to add Accept-Encoding with application/json in axios.post header.
The default of it is gzip
headers: {
"content-type": "application/x-www-form-urlencoded",
'Accept-Encoding': 'application/json'
Authorization: `Basic ${new Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString("base64")}`,
}
I am trying to send post request to a url on which authorization of type API Key is enabled. I am able to send request through the post man. The API is responding perfectly fine, but when I come to fetch in Vuejs. I am unable to send the POST request using fetch.
Screenshot of POSTMAN is attached.
The tried code which I am using in Vuejs is:-
const requestOptions = {
method: "POST",
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-API-Key":"3C68F15FF89132BF254E5FB648FCA",
},
body: JSON.stringify({
name: this.name,
phonenumber: this.phoneNumber,
msg: this.message,
}),
};
let response = await fetch(
"https://auto.toxiclabs.net/webhook/d6121492-4b9c-4dc2-908f-991001b20b61",
requestOptions
);
The error I am getting
Anyone who can tell me what actually is wrong in my code ?
https://marmelab.com/react-admin/Authorization.html
Hi, I was follow this AUTH_GET_PERMISSIONS to do the permissions but it come out this error when I want to login:
It returned the message "Invalid Token Specified" error message.
This is the code for making the errors:
is it related with this code?:
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
}
The expected result:
It will login to the page & with the permissions to display the menu items based on the logged in users.
In your response you have access_token: 'token_value' as property name, but then in code you are destructing the function argument with .then(( {token} ))... as property name. So the value is undefined.
I'm using react native fetch to make a post http request with graphql data to a graphql server endpoint. When starting up my graphql server and calling fetch with a POST in my react native app, I'm getting the following error:
TypeError: Network Request Failed at XMLHttpRequest in react native app
Request code
let graphqlServer = config.graphQLServerUrl;
const graphQLFetcher = (graphQLParams, requestType, token) => {
let body = null; //earlier i used var body =' '; //blank value --null & blank makes a different
let headers = null;
body = graphQLParams;
headers = {
'Accept': 'application/json',
'Content-Type': 'application/graphql',
'Authorization': 'Bearer ' + token
};
return fetch(graphqlServer, {
method: requestType,
headers: headers,
body: graphQLParams,
});
};
Data
qraphQLParams
query {
login(userName: ${credentials.userName}, passWord: ${credentials.passWord})
}
,
Any ideas?
I managed to get this to work by simply JSON.stringify the body of the request.
So..
graphQLParams = `query login{
login(input: {userName: "${obj.input.userName}", passWord: "${obj.input.passWord}" }) {
token
}
}
`
body = JSON.stringify({
query: graphQLParams
});