axios post from lambda function not working - node.js

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

Related

How to file using formdata and axios in node js

This is my code:
async function uploadDocForPlagScan(params) {
try {
console.log(params);
const token = await getTokenForDocumentUpload();
const { data: arr } = await axios.get(
"https://kmsmediasvcstorage.blob.core.windows.net/knowledgesfqueryuat/6-P.pdf",
{ responseType: "arraybuffer" }
);
const apiKey = "idF******************";
const fileName = "WHNTMB.pdf";
const filePath = path.join(__dirname, "WHNTMB.pdf");
const fileContent = await fs.readFileSync(filePath);
const formData = new FormData();
formData.append("fileUpload", fileContent, fileName);
formData.append("language", "en");
const headers = {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${apiKey}`,
};
const response = await axios.post(
`https://api.plagscan.com/v3/documents?access_token=${token.data}`,
{ fileUpload: formData },
{ headers }
);
console.log(response.data);
} catch (error) {
p = error;
}
}
I tried to upload file in node js by making post call in https://api.plagscan.com/v3/documents?access_token=amdsfa

POST http://localhost:5000/api/device 404 (Not Found) even url is correct

I have a problem with axios. When i send post request axios returns me an error
POST http://localhost:5000/api/device 404 (Not Found)
But when when I send GET request everything is ok.
Could you help me
It is my code
const $authHost = axios.create({
baseURL:process.env.REACT_APP_API_URL
})
const authInterceptor = config => {
config.headers.authorization = `Bearer ${localStorage.getItem('token')}`
return config
}
$authHost.interceptors.request.use(authInterceptor)
export const createDevice = async (device) => {
let config = {
headers: {
'Content-Type': 'application/json',
}
}
const {data} = await $authHost.post('/api/device', device, config)
return data
}
export const fetchDevices = async () =>{
const {data} = await
const addDevice = () =>{
const formData = new FormData()
formData.append('name', name)
formData.append('price', `${price}`)
formData.append('img', file)
formData.append('brandId', devices.selectedBrand.id)
formData.append('typeId', devices.selectedType.id)
formData.append('info', JSON.stringify(info))
createDevice(formData).then(data => onHide())
}

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

Axios - How to get the Cookies from the response?

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

Request form URL encoded within a request

I'm trying to make a request form_url_encoded when requesting a request, but it's giving me an error on the console that is already on port 3000, it's giving some error but not finding it, because if I leave the default as in the doc, it runs normal and opens at the door. I get:
Error: connect ECONNREFUSED
const express = require("express");
const router = express.Router();
const axios = require("axios");
const qs = require("qs");
const requestBody = {
refresh_token:
"1000.51355b1f8f5a8176026525670b5bbf3e.93c56a6bd3cb4589bd65b334810848cf",
client_id: "1000.KS2QNMSAQIMS74YBGZROSXD8QD3GWO",
client_secret: "06abfcc05409c430fb15252d47e8d9fe03a3582cbc",
rant_type: "refresh_token",
};
const config = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
const config2 = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post(
"/crm7/sell_order",
{ test: "test" },
config2
)
.then((res) => {
console.log(res);
return axios.post("https://accounts.blue.com/oauth/v2/token", qs.stringify(requestBody), config);
})
.then((res) => {
console.log(res)
})
.catch((err) => {
console.log(err)
});
module.exports = router;

Resources