I am trying to get some details of mail that I have sended using google-api. I am using messageId that I have received after sending email. I am expection the data to be in json format.
Here is the Nodejs code for reading sended mail:
app.post("/readMail", async (req, res)=>{
let messageId = req.body.messageId;
try {
const oAuth2Client = new google.auth.OAuth2(
properties.GOOGLE_CLIENT_ID,
properties.GOOGLE_CLIENT_SECRET,
);
oAuth2Client.setCredentials({ refresh_token: properties.REFRESH_TOKEN });
const { token } = await oAuth2Client.getAccessToken();
const generateConfig = (url, accessToken) => {
return {
method: "get",
url: url,
headers: {
Authorization: `Bearer ${accessToken} `,
"Content-type": "application/json",
},
};
};
const url = `https://gmail.googleapis.com/gmail/v1/users/Abhisek721#gmail.com/messages/${messageId}`;
const config = generateConfig(url, token);
const response = await axios(config);
let data = await response.data;
res.json(data);
} catch (error) {
res.send(error);
}
})
And This the response:
"\u001f\ufffd\b\u0000\u0000\u0000\u0000\u0000\u0002\ufffd\ufffdUmo\ufffd:\u0014\ufffd\ufffd_a\ufffdu\ufffds\u0012^\ufffdN\ufffd\u0006\t/a\ufffd2\ufffd\ufffd\ufffdީr\u0012\ufffd\u0018\ufffd8rLB6\ufffd\ufffd_'P\ufffdݱ\ufffd^]\ufffd\ufffd\ufffd\ufffd\ufffd=\ufffd\ufffd\ufffd\u000e\ufffd\n\ufffd*\ufffd\ufffd\ufffd\ufffdu\ufffd:\\75\ufffd]C\ufffdrU\ufffdD\ufffd1\ufffdW4(r0\ufffd\ufffdDj\ufffd%\ufffd\ufffdd\ufffd\u0019\ufffd*\ufffd\ufffdR\ufffdD$\ufffd\ufffd(\u0000:!\"\u0014\ufffd8r\ufffd\ufffd\ufffd!\ufffd8\u0004$Nv!"
I was expecting to get something like json data.
Related
A post request with axios get http error 500.
This is the code:
async function getUserTokenByRefresh(refreshToken) {
const encodedStr = base64Encode(`${process.env.EBAY_SANDBOX_APPID}:${process.env.EBAY_SANDBOX_CERTID}`);
const auth = `Basic ${encodedStr}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: auth
}
};
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};
const testing = true;
const url = testing
? "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
: "https://api.ebay.com/identity/v1/oauth2/token";
try {
const response = await axios.post(
url,
data,
options
);
console.log(JSON.stringify(response));
}
catch (e) {
console.log(JSON.stringify(e));
}
}
This is the error message:
{
"message": "Request failed with status code 500",
"code": "ERR_BAD_RESPONSE",
"status": 500
}
This is the error message in json format.
I don't know what's wrong in the code.
Can you check it?
Data should be encoded.
async function getUserTokenByRefresh(refreshToken) {
const encodedStr = base64Encode(`${process.env.EBAY_SANDBOX_APPID}:${process.env.EBAY_SANDBOX_CERTID}`);
const auth = `Basic ${encodedStr}`;
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: auth
}
};
const data = {
grant_type: "refresh_token",
refresh_token: refreshToken
};
const testing = true;
const url = testing
? "https://api.sandbox.ebay.com/identity/v1/oauth2/token"
: "https://api.ebay.com/identity/v1/oauth2/token";
try {
const response = await axios.post(
url,
//ENCODED DATA
new URLSearchParams(data),
options
);
console.log(JSON.stringify(response));
}
catch (e) {
console.log(JSON.stringify(e));
}
}
in Node.js, I am trying to send a POST request with Axios to Twilio and send an SMS message to my phone. But I am getting an 'error: Authentication Error - No credentials provided ? Here is the code:
const body = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Body: 'hi from vsc',
To: toNumber,
From: fromNumber,
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
};
exports.axios = () => axios.post(`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`, body, headers).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
I also tried to use the same parameters with POSTMAN and the POST request is successful. I also tried to encode my authorization username and password to Base 64, but with no success.
I wrote to Twilio customer help but haven`t received any replies yet.
Axios makes an auth option available that takes an object with username and password options. You can use this with the username set to your account SID and password set to your auth token.
The headers object should be sent as the headers parameter of a config object in the third parameter to axios.post. Like so:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
};
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
headers,
auth: {
username: accountSID,
password: authToken
}
}
}).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
Headers is actually a field of config, try something like this:
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
Authorization: `Basic ${accountSID}:${authToken}`,
}
}
axios.post(URL, data, config).then(...)
Or this (general example calling a Twilio endpoint)
const axios = require('axios');
const roomSID = 'RM1...';
const participantSID = 'PA8...';
const ACCOUNT_SID = process.env.ACCOUNT_SID;
const AUTH_TOKEN = process.env.AUTH_TOKEN;
const URL = "https://insights.twilio.com/v1/Video/Rooms/"+roomSID+"/Participants/"+participantSID;
axios({
method: 'get',
url: URL,
auth: {
username: ACCOUNT_SID,
password: AUTH_TOKEN
}
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Working code:
const params = new URLSearchParams();
params.append('Body','Hello from vcs');
params.append('To',toNumber);
params.append('From',fromNumber);
exports.axios = () => axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${accountSID}/Messages.json`,
params,
{
auth: {
username: accountSID,
password: authToken,
},
},
).then((res) => {
console.log(res, 'res');
}).catch((err) => {
console.log(err);
});
The previous solutions did not work for me. I encountered either the Can't find variable: btoa error or A 'To' phone number is required..
Using qs worked for me:
import qs from 'qs';
import axios from 'axios';
const TWILIO_ACCOUNT_SID = ""
const TWILIO_AUTH_TOKEN = ""
const FROM = ""
const TO = ""
const sendText = async (message: string) => {
try {
const result = await axios.post(
`https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
qs.stringify({
Body: message,
To: TO,
From: FROM,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: TWILIO_ACCOUNT_SID,
password: TWILIO_AUTH_TOKEN,
},
},
);
console.log({result});
} catch (e) {
console.log({e});
console.log({e: e.response?.data});
}
};
I need to get an authentication cookie from a website, while performing my request using Axios.
var axios = require('axios');
const authentication = async(login, password) => {
var data = `MYPAYLOAD${login}[...]${password}`;
var config = {
method: 'post',
url: 'https://mywebsite.com/login.aspx',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data : data,
};
try {
return await axios(config, {withCredentials: true});
} catch (error) {
console.log('Error: cannot authenticate...')
}
}
const init = async() => {
const login = 'LOGIN';
const password = 'PASSWORD';
const response = await authentication(login, password);
console.log(response);
}
init()
I'm receiving some Cookies that I need, but the one including the auth token is missing.
If I use exactly the same settings in Postman, I'm receiving the AUTH_TOKEN I'm looking for.
Where am I wrong?
Thanks
Thank you for your time.
I'm trying to use OAuth2 in discord, but I'm having a hard time figuring out how to retrieve the username.
Can someone please tell me how to do it?
code
const fetch = require('node-fetch');
const express = require('express');
const app = express();
app.get('/', async ({ query }, response) => {
const { code } = query;
if (code) {
try {
const oauthResult = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: new URLSearchParams({
client_id: process.env['ci'],
client_secret: process.env['cs'],
code,
grant_type: 'authorization_code',
redirect_uri: `https://oauth.aiueominato1111.repl.co`,
scope: 'identify',
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
const oauthData = await oauthResult.json();
const userResult = await fetch('https://discord.com/api/users/#me', {
headers: {
authorization: `${oauthData.token_type} ${oauthData.access_token}`,
},
});
console.log( await userResult.json());
} catch (error) {
// NOTE: An unauthorized token will not throw an error;
// it will return a 401 Unauthorized response in the try block above
console.error(error);
}
}
return response.sendFile('index.html', { root: '.' });
});
app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
thank you
You already have the JSON data (from await userResult.json()) with it you can either get the property from the object or destructure it.
Getting property
const user = await userResult.json();
const username = user.username
Destructuring
const { username, id } = await userResult.json()
You can find out more about what properties you can extract from the Discord documentation
After successfully integrating a 3rd party REST Oauth Api, now i am trying to convert the api logic into a graphql query but i'm kind of stuck on how best to architect the query.
From a REST perspective, i have something like this that works 100%
app.get("/auth/redirect", async (req: Request, res:Response) => {
const code = req.query.code
const { access_token, account_id } = await getTokens({
code,
clientId,
clientSecret,
})
try{
const result = await axios
.get(
`https://api.specificservice.dev/helloworld/id/v1/accounts?accountId=${account_id}`,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${access_token}`,
},
}
)
console.log('Fetching user..', result.data)
return result.data
}
catch (error: any) {
let message = error.result.data
console.log(message)
return message
}
})
from Graphql, I've got a sketch like this.
getPlatform: async (_: any, _args: any, { req }: any) => {
const clientId = "test"
const clientSecret = "test"
const code = req.query.code
const { access_token, account_id } = await getTokens({
code,
clientId,
clientSecret,
})
try{
const result = await axios
.get(
`https://api.specificservice.dev/helloworld/id/v1/accounts?accountId=${account_id}`,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Bearer ${access_token}`,
},
}
)
console.log('Fetching user..', result.data)
return result.data
}
catch (error: any) {
let message = error.result.data
console.log(message)
return message
}
},
How can I refactor this to suit what I'm trying to do from the rest endpoint