How to pass headers in axios as secret-key - javascript

I am using jsonbin.io and hosted a json data as private bin.
I am calling a axios get request to fetch that data. I have to pass my secret-key in headers as
headers{
secret-key: mysecretkey
}
but axios does not allow key in header as secret-key
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
secret-key: secretKey,
},
});
console.log(response); };
secret-key gives error at compile time and "secret-key" can not fetch data what should i do now ?

secret-key is not a valid identifier in JavaScript, as they cannot contain hyphens (see the specification for more details.
In your case, you can simply put the name of your header in quotes, like this:
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
"secret-key": secretKey,
},
});
console.log(response);
};

it should be
const fetchPhotosFlocal = async () => axios.get(localUrl, {
headers: {
'secret-key': secretKey,
},
});
const resp = await fetchPhotosFlocal();
console.log(resp);

Problem solved i checked their documentation they are passing secret_key in string code.
req.setRequestHeader("secret-key", "<SECRET_KEY>");
This runs fine
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
"secret-key": secretKey,
},
});
console.log(response); };

Related

Axios post IN Javascript

I am attempting an axios POST, using Node js.
making a call to the api is in two steps, first doing a post to get an access token, then a get with that access token.
I have accomplished the call in c#
var baseUri = new Uri("www.example.com");
var requestToken = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(baseUri, "oauth/token"),
Content = new StringContent("grant_type=client_credentials&client_id=someIDnumHere&client_secret=somePassword")
};
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = client.SendAsync(requestToken).Result)
{
using (HttpContent content = response.Content)
{
var json = content.ReadAsStringAsync().Result;
dynamic jsonData = JsonConvert.DeserializeObject<dynamic>(json);
var accessy = jsonData.access_token;
accessTokens.Add(accessy.ToString());
}
}
and even Firefox REST Client
but I have failed (bad request) in node JS
this is what I tried.
let urly = 'https://example.com';
const newPost = {
body: 'grant_type=client_credentials&client_id=someIDHereclient_secret=somePasswordHere'
};
const sendPostRequest = async () => {
try {
const resp = await axios.post(urly, newPost);
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
sendPostRequest();
any help is appreciated.
Thanks to # zemaj
let urly = "https://example.com";
const sendPostRequest = async () => {
try {
const resp = await axios.post(
urly,
"grant_type=client_credentials&client_id=someIDHereclient_secret=somePasswordHere"
);
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
sendPostRequest();

How to get PDF from lambda to React

I am trying to use pdf-lib to write to a government PDF form. The form is located on a government website so I have to use a server to server architecture due to CORS. I have set up a lambda function to grab the form and send the PDF Bytes as a response. The problem is when I get it on the front end and make an Object URL it does not appear on the front end as anything I am confused what I am doing wrong.
Here is the lambda code:
const { PDFDocument } = require('pdf-lib');
const axios = require('axios');
/**
* #type {import('#types/aws-lambda').APIGatewayProxyHandler}
*/
exports.handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
async function fillForm() {
const formUrl = 'https://pdf-lib.js.org/assets/dod_character.pdf';
const formPdfBytes = await axios.get(formUrl, {
responseType: 'arraybuffer',
});
const formPdfBytesArrayBuffer = formPdfBytes.data;
const marioUrl = 'https://pdf-lib.js.org/assets/small_mario.png';
const marioImageBytes = await axios.get(marioUrl, {
responseType: 'arraybuffer',
});
const marioImageBytesArrayBuffer = marioImageBytes.data;
const emblemUrl = 'https://pdf-lib.js.org/assets/mario_emblem.png';
const emblemImageBytes = await axios.get(emblemUrl, {
responseType: 'arraybuffer',
});
const emblemImageBytesArrayBuffer = emblemImageBytes.data;
const pdfDoc = await PDFDocument.load(formPdfBytesArrayBuffer);
const marioImage = await pdfDoc.embedPng(marioImageBytesArrayBuffer);
const emblemImage = await pdfDoc.embedPng(emblemImageBytesArrayBuffer);
console.log(marioImage, emblemImage);
const form = pdfDoc.getForm();
console.log(form);
const pdfBytes = await pdfDoc.save();
return pdfBytes;
}
const docURL = await fillForm();
return {
statusCode: 200,
// Uncomment below to enable CORS requests
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
},
body: JSON.stringify({ data: { docURL } }),
};
};
Here is my front end code that is currently not causing anything to display:
const handleButtonClick = async () => {
try {
const pdfBytes = await fetchPDF();
const bytes = new Uint8Array(pdfBytes.docURL);
const blob = new Blob([bytes], { type: 'application/pdf' });
const docUrl = URL.createObjectURL(blob);
setPdf(docUrl);
} catch (err) {
console.log(err);
}
};

Authentication in headers/fetch

I am stuck and looking for someone to help me. I've been trying to Authorize my fetch request but it always return an error. Is there someone who could explain in what way authorize header?
import { ref } from "vue";
const getAllData = () => {
const data = ref();
const entry = "user:pass";
const fetchAllData = async function () {
const res = await fetch("http://127.0.0.1:8000/articles/", {
method: "GET",
headers: {
// How to authorize?
Authorization: Bearer ${entry},
},
});
data.value = await res.json();
console.log(data.value);
};
return { data, fetchAllData };
};
export default getAllData;

OpenWeathermap country codes code problem "city not found"

I'm writing code for a weather journal app. The thing is when I pass to fetch method the URL of the site of openweathermap.com with the zip code and country code way it only accepts the country code as the US it never accepts another country. I tried so many but it never accepts any of those it only returns the data object of forecast to the US and for any other country it just shows the message city not found. Here is my code:
const generate = document.getElementById('generate').addEventListener('click', function(){
const zip = document.getElementById('zip').value;
const countryCode = document.getElementById('countryCode').value;
endPointData(zip,countryCode,apiKey);
})
const endPointData = async (zip,countryCode,apiKey) => {
const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},${countryCode}&appid=${apiKey}`);
try{
const data = await res.json();
console.log(data);
}
catch(error){
// appropriately handles the errors.
console.log("error",error);
}
}
const postData = async (url='', data = {}) => {
const response = await fetch(url,{
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data),
});
try{
const newData = await response.json();
return newData;
}catch(error){
console.log("error",error);
}
}
Working fine for me in other countries as well.
const apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const zipCode = "110007";
const countryCode = "IN";
const endPointData = async (zipCode, countryCode, apiKey) => {
const URL = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},${countryCode}&appid=${apiKey}`;
const res = await fetch(URL);
try {
const data = await res.json();
console.log(data);
}
catch(error){
// appropriately handles the errors.
console.log("error",error);
}
}
endPointData(zipCode, countryCode, apiKey);
console.log your URL variable. Maybe your country code is empty.
The API falls back to US as default when country code is not specified.
https://openweathermap.org/current#zip
Try it at postman first (https://www.postman.com/)!

How can I solve msg: 'Signature for this request is not valid.' from binance API?

I am trying to create a test order using Binance API but I have this error message msg: 'Signature for this request is not valid.' I tried to get the signature using the secret key and timestamp = Date.now() but didn't work.
My code is:
const credentials = require('./credentials');
const crypto = require('crypto');
function testNewOrder(symbol,side,type,timeInForce,quantity,price) {
const url = credentials.urlTest;
let timeStamp = Date.now();
let signature = crypto.createHmac('sha256', credentials.secretKeyTest).update(`timestamp=${timeStamp}`).digest('hex')
console.log(signature,timeStamp,timeStamp2);
fetch(`${url}/api/v3/order/test?symbol=${symbol}&side=${side}&type=${type}&timeInForce=${timeInForce}&quantity=${quantity}&price=${price}&timestamp=${timeStamp}&signature=${signature}`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-MBX-APIKEY": credentials.apiKeyTest
},
}).then(response => {
return response.json();
}).then( data=> {
console.log(data);
}).catch(err => {
console.log(err)
})
}
testNewOrder('BTCUSDT','SELL','LIMIT','GTC','0.02','42000');
I was also facing same issue, Hope this will help
import { createHmac } from "crypto";
const SECRET = "";
export const addSignature = (params) => {
// Object to query string
const queryString = Object.keys(params)
.map((key) => `${key}=${params[key]}`)
.join("&");
const signature = createHmac("sha256", SECRET)
.update(queryString)
.digest("hex");
return {
...params,
signature,
};
};
addSignature({
symbol: "BTC",
// ...
});

Categories