axios post request getting error 500 fdretdrgfdg - node.js

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));
}
}

Related

I am getting weird data as a response

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.

Axios POST request to Twillio returns with an Authentication Error?

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});
}
};

How can I send different request in intercepter?

I'm trying to send different request in interceptor
I want to send accessToken in request header authorization for every request except one case
so I write this code in interceptor request.use
config.headers = {authorization: `Bearer ${accessToken}`};
but if this error occurred
error.response.data.code === 'expired'
I want to send refreshtoken in header authorization not accesstoken
so I write this code in interceptor.response.use.error
const { data } = await axios.post(
`${Config.API_URL}/user/refreshToken`,
{},
{ headers: { authorization: `Bearer ${refreshToken}` } }
);
this is my code
useEffect(() => {
axios.interceptors.request.use(async (config: any) => {
const accessToken = await EncryptedStorage.getItem("accessToken");
config.headers = { authorization: `Bearer ${accessToken}` };
return config;
});
axios.interceptors.response.use(
(response) => {
return response;
},
async (error) => {
const {
config,
response: { status },
} = error;
if (status === 419) {
if (error.response.data.code === "expired") {
const originalRequest = config;
const refreshToken = await EncryptedStorage.getItem("refreshToken");
const { data } = await axios.post(
`${Config.API_URL}/user/refreshToken`,
{},
{ headers: { authorization: `Bearer ${refreshToken}` } }
);
return axios(originalRequest);
}
}
return Promise.reject(error);
}
);
}, [dispatch]);
how can i fix my code?
if i use my code if error.response.data.code === 'expired'
the headers.authorization accesstoken is still being requested.
Make it so your request interceptor only sets a default authorization header without overriding anything already present
axios.interceptors.request.use(async (config) => {
const accessToken = await EncryptedStorage.getItem("accessToken");
return {
...config,
headers: {
authorization: `Bearer ${accessToken}`,
...config.headers
}
}
});
You could also avoid making the getItem() request entirely which might save a little time
axios.interceptors.request.use(async (config) => {
if (!config.headers.authorization) {
config.headers.authorization = `Bearer ${await EncryptedStorage.getItem("accessToken")}`
}
return config;
});

'Missing or duplicate parameters' in Access Token Response

I'm trying to fetch the OAuth access token with the lambda function but getting fhe following error:
data: {
error: 'invalid_request',
error_description: 'Missing or duplicate parameters'
}
This is the code:
var axios = require("axios").default;
exports.handler = async (event) => {
var options = {
method: 'POST',
url: 'https://******/auth/oauth/v2/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: {
grant_type: 'client_credentials',
client_id: '*********',
client_secret: '******'
}
};
try {
const resp = await axios.request(options);
console.log(resp.data)
} catch (err){
console.error(err);
}
};
When I try to run the request with the Postman it returns the valid token.
As stated by #derpirscher, I had to properly serialize the data object using 'qs' library. After that I was able to fetch the access token successfully.
var axios = require("axios").default;
const qs = require('qs');
exports.handler = async (event) => {
var data = {
grant_type: 'client_credentials',
client_id: '*********',
client_secret: '************'
};
var options = {
method: 'POST',
url: 'https://************/auth/oauth/v2/token',
headers: {'content-type': 'application/x-www-form-urlencoded'},
data: qs.stringify(data)
};
try {
const resp = await axios.request(options);
console.log(resp.data)
} catch (err){
console.error(err);
}
};

Axios and Oauth1.0 - 'status: 400, Bad Request'

I'm new on Nodejs and all the modules related with Node. I've been trying to use axios for send a Oauth1.0 Autorization signature, but i'm getting: response: { status: 400, statusText: 'Bad Request', ...}
import { BASE_URL } from '../../../config/config.js';
import axios from 'axios';
import status from 'http-status';
import OAuth from 'oauth-1.0a';
import { createHmac } from 'crypto';
import dotenv from 'dotenv';
dotenv.config();
const CONSUMERKEY = process.env.consumer_key;
const CONSUMERSECRET = process.env.consumer_secret;
const TOKENKEY = process.env.access_token;
const TOKENSECRET = process.env.token_secret;
export const oauth = OAuth({
consumer: {
key: CONSUMERKEY,
secret: CONSUMERSECRET,
},
signature_method: 'HMAC-SHA1',
hash_function(base_string, key) {
return createHmac('sha1', key)
.update(base_string)
.digest('base64')
},
})
export const token = {
key: TOKENKEY,
secret: TOKENSECRET,
}
const doRequest = async (query) => {
const request_data = {
url: `${BASE_URL}`,
method: 'GET',
params: { q: `${query}` },
};
const authHeader = oauth.toHeader(oauth.authorize(request_data, token));
return await axios.get(request_data.url, request_data.params, { headers: authHeader });
};
const searchU = async (term) => {
return await doRequest(`${term}`);
};
export const userS = async (req, res, next) => {
try {
const { query } = req;
const { data } = await searchU(query.q);
const string = JSON.stringify(data);
const Rs = JSON.parse(string);
const response = {
code: 1,
message: 'sucess',
response: Rs
};
res.status(status.OK).send(response);
} catch (error) {
next(error);
if (error.response){
console.log("Response: ");
console.log(error.response);
} else if(error.request){
console.log("Request: ");
console.log(error.request)
} else if(error.message){
console.log("Message: ");
console.log(error.message)
}
}
};
I've been also trying the solution given On this post: but there's no way I can make this work, no idea what i could be doing wron...
When i try the following code (see below), using Request module (which is deprecated) works well, but I really need to do it with Axios...
const request_data = {
url: `${BASE_URL}`,
method: 'GET',
params: { q: `${query}` },
};
const authHeader = oauth.toHeader(oauth.authorize(request_data, token));
request(
{
url: request_data.url,
method: request_data.method,
form: request_data.params,
headers: authHeader,
},
function(error, response, body) {
console.log(JSON.parse(body));
}
)
Any thoughts on what I'm doing wrong on this?? Thank you very much!!
Refer to the following link for the Request Config for Axios. I believe you need to have the query params after the header in the axios.get()
Axios Request Config
Try, the following and see how it goes:-
return await axios.get(request_data.url, { headers: authHeader }, request_data.params);

Resources