request-promise post request to axios request - node.js

Can you please help me convert the following request to axios request.
const request = require('request-promise');
const data = {name:'pte', age:30}
const options = {secret:'34444'}
const opp = {
method: 'POST',
uri: 'https://something',
headers: { 'content-type': 'application/json' },
options,
body: JSON.stringify(data),
};
return request(opp);

const axios = require('axios')
const url = 'https://something'
const data = { name : 'pte', age : 30 }
const options = {
headers : {
'content-type' : 'application/json'
}
}
axios.post(url, data, header)

Related

Send post request with Axios with body and headers

I am working on a project where I need to create a short URL for a link using bitly.
I got success by using the request package of Nodejs.
This is what I have done so far.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
var options = {
url: api_url,
method: "POST",
headers: headers,
body: dataString,
};
request(options, (error, body) => {
if (error) {
return res.status(404).send(error);
}
return res.render("index", { error: "", data: JSON.parse(body.body) });
});
my question is how can we use Axios instead of the request package because the request package is deprecated.
I tried but did not get success.
const token = process.env.BITLY_ACCESS_TOKEN;
let headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
};
var dataString = `{ "long_url": "${req.body.url}"}`;
const api_url = "https://api-ssl.bitly.com/v4/shorten";
const response = await axios.post(
api_url,
{ long_url: req.body.url },
{
headers: headers,
}
);
return res.render("index", { error: "", data: response });
I am getting errors like the body is not defined.
Please help me. Thank you!
const response = await axios.post(api_url, dataString, {
headers: headers,
});
console.log(response.data);
return res.render("index", { error: "", data: response.data });

POST File in AXIOS NodeJs

Post file as raw body in AXIOS NodeJS. I tried many ways to achieve this but none of them worked.
What i have tried ?
var file = fs.readFileSync("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg").toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg",{encoding:"utf8"}).toString();
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.readFileSync("a.jpg");
file = Buffer.from(file).toString('utf8')
var body = await axios({ method: 'POST', url : "myUrl", data : file });
var file = fs.createReadStream("a.jpg");
var body = await axios({ method: 'POST', url : "myUrl", data : file });
But none of them worked as i wanted.
Actual working example from JQuery AJAX in Browser
var fileupload = $("#inpFile")[0];
var file = fileupload.files[0];
$.ajax({
url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
type: 'POST',
success: function (response) {
DisplayMessage(response);
},
data: file,
contentType: false,
processData: false
});
Have you tried setting the content-type header?
Per Talg123 I found that if you set contentType to false in jQuery it might be equivalent to multipart/form-data.
client side:
async function main(){
try{
const buffer = new ArrayBuffer(8);
const data = new FormData();
const blob = new Blob([buffer],{type : 'multipart/form-data'});
data.append('data', blob);
const options = {
url: "https://hookb.in/b9gqlwbZeaT3DDogQ7Om",
method: 'POST',
headers: { 'content-type': 'multipart/form-data' },
data
};
let result = await axios(options);
console.log(result);
}catch(e){
console.error("error",e);
}
}
main()
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
server side per https://github.com/axios/axios/issues/1006#issuecomment-584840380
const axios = require('axios');
const FormData = require('form-data');
// Where buffer is a file
formData.append('file', buffer);
// Added a promise version like seen in earlier comments to get this
const contentLength = await formData.getLength();
await axios(`<ENDPOINT>`, {
method: 'POST',
baseURL: <BASE_URL>,
params: {
fileName: '<FILE_NAME>.png'
},
headers: {
authorization: `Bearer <TOKEN>`,
...formData.getHeaders(),
'content-length': contentLength
},
data: formData
});
js fiddle for image/jpeg
https://jsfiddle.net/bn7yLh61/

axios post from lambda function not working

Trying to post from aws lambda using axios but it's not working...
I'm not really sure what's going on, but on postman this works.
In the call not configured correctly?
exports.handler = async (event) => {
const body = parseBody(event.body);
body.phone_number = decrypt(body.phone_number);
const username = 'SOMETOKEN';
const password = 'SOMEAPIKEY';
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64');
const axios = require('axios');
const url = 'some_url';
const headers = {
'Authorization': `Basic ${token}`
};
const requestbody = {
To: '+12122806392',
From: '+12064622015'
};
const params = {headers: headers, body:requestbody};
console.log('posting');
axios.post(url, {
headers: headers,
body: requestbody
})
.then((response) => {
console.log(response);
}, (error) => {
console.log(error);
});
}

Spotify Api Auth unsupported_grant_type

I'm working on integrating spotify and I'm making my own api. I can't understand why my request is not working. It works fine in python but not when I use express.
I get this response body :
{"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"}
Express :
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fetch = require('node-fetch');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.listen(80);
app.post('/v1/spotify/api/token', function(req, res) {
let body = req.body
let redirect_uri = body.redirect_uri
let code = body.code
let data = {
grant_type:'authorization_code',
redirect_uri:redirect_uri,
code:code
}
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization':'Basic *client_id:client_secret*',
'Content-Type':'application/x-www-form-urlencoded'
},
body: JSON.stringify(data)
}).then(r => r.json().then(data => res.send(data)))
});
Python:
r = requests.post("https://accounts.spotify.com/api/token",
data={
"grant_type":"authorization_code",
"redirect_uri":*redirect_uri*,
"code":*code*
},
headers = {
"Authorization": "Basic *client_id:client_secret*",
'Content-Type':'application/x-www-form-urlencoded'}
)
In your script of Node.js, data is sent as a string value. So how about this modification?
Modified script
Please modify the object of data as follows and try again.
// Below script was added.
const {URLSearchParams} = require('url');
const data = new URLSearchParams();
data.append("grant_type", "authorization_code");
data.append("redirect_uri", redirect_uri);
data.append("code", code);
fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization':'Basic *client_id:client_secret*',
'Content-Type':'application/x-www-form-urlencoded'
},
body: data // Modified
}).then(r => r.json().then(data => res.send(data)))
Reference:
Post with form parameters of node-fetch
If this didn't work, I apologize.
I had to put the client_id and client_secret in the body and not in Authorization header.
try {
const body = {
grant_type: "client_credentials",
client_id: <YOUR_ID>,
client_secret: <YOUR_SECRET>,
};
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams(body),
});
console.log({ response });
} catch (err) {
console.log({ err });
}

How to correctly handle Params and Querys in Axios?

I'm consuming an API with NODEJS and using the axios to do the "get" ...
In NODEJS we call "params" everything that comes before the "?" Character, and we call the "query" everything that goes after the "?" Character, such as:
https://www.url.com/testing.xsjs?QueryName1='test1,test1'&QueryName2=1
The problem I'm having in Axios is that it does not create the url correctly, which the correct URL should be:
https: //www.url.comho/fatSales.xsjs?Shop='shop1,shop2,shop3'&PeriodoDe=201801&PeriodoAte=201807&Kpi='kp1,kp2,kp3'& Select = NUCOMPETEC
But the url he is creating for me is this:
https://www.apiUrl.com/Shop=shop1, + shop2, + shop3&PeriodoDe=201801&PeriodoAte=201807&Kpi=kp1,+kp2,+kp3&Select=NUCOMPETEC
I have some issues with this URL that it creates that are as follows:
1) Shop and Kpi it creates the "+" character
2) It does not add the parameter (NODEJS) before the "?" Character ...
Remembering that:
Shop and Kpi (It's an array with 1 or * elements)
const axios = require('axios');
const Qs = require('qs');
class ApiDAO {
constructor(xsjs, shoppingId, periodOf, periodUntil, kpi, select){
this.xsjs = xsjs;
this.shoppingId = shoppingId;
this.periodOf = periodOf;
this.periodUntil = periodUntil;
this.kpi = kpi;
this.select = select;
}
configAxios(){
return axios.create({
method: 'GET',
responseType: 'json',
responseEncoding: 'utf8',
headers: {
'Content-Type': "application/json",
'Cache-Control': "no-cache",
Authorization: "",
Apikey: "",
},
params: {
xsjs: this.xsjs,
Shop: this.shoppingId,
PeriodoDe: this.periodOf,
PeriodoAte: this.periodUntil,
Kpi: this.kpi,
Select: this.select
},
});
}
async getResponseAxios(){
return await this.configAxios().get('https://www.apiUrl.com/');
}
}
module.exports = () => { return ApiDAO };
Are you stringifying your params? Can you try the following:
const axios = require('axios');
const Qs = require('qs');
class ApiDAO {
constructor(xsjs, shoppingId, periodOf, periodUntil, kpi, select){
this.xsjs = xsjs;
this.shoppingId = shoppingId;
this.periodOf = periodOf;
this.periodUntil = periodUntil;
this.kpi = kpi;
this.select = select;
}
configAxios(url){
return axios.get({
method: 'GET',
url: url,
responseType: 'json',
responseEncoding: 'utf8',
headers: {
'Content-Type': "application/json",
'Cache-Control': "no-cache",
Authorization: "",
Apikey: "",
},
params: {
xsjs: this.xsjs,
Shop: this.shoppingId,
PeriodoDe: this.periodOf,
PeriodoAte: this.periodUntil,
Kpi: this.kpi,
Select: this.select
},
});
}
async getResponseAxios(){
return await this.configAxios('https://www.apiUrl.com/');
}
}
module.exports = () => { return ApiDAO };
Or if you want to use axios create, pass the URL in earlier as an option field. I don't think it's an error with the other params.

Resources