Put API KEY in axios - react-native

I just started learn React but I have problem when I trying to make a request to the CoinMarketCap API with axios and tried several ways to set my API key. I have also also tried on Postman but message appears API key missing.
export const apiBaseURL = 'https://pro.coinmarketcap.com';
Tried like this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`,
{ headers =
{ 'X-CMC_PRO_API_KEY': 'apicode', }
})
this
dispatch({ type: FETCHING_COIN_DATA })
let config = { 'X-CMC_PRO_API_KEY': 'apicode' };
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map`, { headers: config })
and this
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?X-CMC_PRO_API_KEY=apicode`)
Thank you

The short answer to adding an X-Api-Key to an http request with axios can be summed up with the following example:
const url =
"https://someweirdawssubdomain.execute-api.us-east-9.amazonaws.com/prod/custom-endpoint";
const config = {
headers: {
"Content-Type": "application/json",
},
};
// Add Your Key Here!!!
axios.defaults.headers.common = {
"X-API-Key": "******this_is_a_secret_api_key**********",
};
const smsD = await axios({
method: "post",
url: url,
data: {
message: "Some message to a lonely_server",
},
config,
});
Adding the key to the default headers was the only way I could get this to work.

Use CMC_PRO_API_KEY as a query parameter, instead of X-CMC_PRO_API_KEY:
dispatch({ type: FETCHING_COIN_DATA })
return axios.get(`${apiBaseURL}/v1/cryptocurrency/map?CMC_PRO_API_KEY=apicode`)

I realize this has been solved; for the sake of alternatives here is how I did it. I created a instance of axios in /includes/axios:
import axios from "axios";
const instance = axios.create({
baseURL: "https://example.com/api",
headers: {
"Content-Type": "application/json",
"x-api-key": "****API_KEY_HERE****",
},
});
export default instance;
Now axios can be imported anywhere in the project with the give configuration. Ideally you want to add your secret to the ENV variable for security reasons.

Related

multipart/form-data request failing in react-native

I get the following error when I set the 'Content-Type' as 'multipart/form-data' in react-native.
Below is my code -
const formData = new FormData();
formData.append('org_id', org_id);
formData.append('ans', userAns);
formData.append('remark', userRemark);
formData.append('img', userImg);
files.forEach(file => {
formData.append('files', {
name: file.fileName,
type: file.type,
uri: file.uri,
});
});
const resp = await multiPartInstance({
method: 'PUT',
url: `${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
data: formData,
});
return Promise.resolve(true);
I am using axios for calling apis. multiPartInstance is an axios instance -
const multiPartAccessToken = async (config: AxiosRequestConfig) => {
config.headers = {
Accept: 'application/json',
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data;',
};
config.timeout = 30000;
return config;
};
I've tried the above with fetch also but I keep getting the same error. The strangest part is that this request hits the server, server sends a response too but I get this error react-native side. I've noticed if I don't use FormData I don't get any error. But I need to use FormData as I have to upload image files.
Environment Details -
Windows version 21H2 (OS Build 22000.376)
react-native 0.66.3
react 17.0.2
axios ^0.24.0
react-native-image-picker ^4.3.0 (used for selecting images)
Flipper version 0.99.0
I've tried the solutions posted on below forums but they didn't work for me.
request formData to API, gets “Network Error” in axios while uploading image
https://github.com/facebook/react-native/issues/24039
https://github.com/facebook/react-native/issues/28551
I am as follow and works perfectly:
const oFormData = new FormData();
images.map((val, index) => {
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
});
return axios.post(postServiceUrl, oFormData);
Somehow react-native-blob-util doesn't give this error. I modified my code as below -
import ReactNativeBlobUtil from 'react-native-blob-util';
const fileData = files.map(file => {
return {
name: 'files',
data: String(file.base64),
filename: file.fileName,
};
});
try {
const resp = await ReactNativeBlobUtil.fetch(
'PUT',
`${apiBaseUrl}/installation/${Iid}/answer/${qid}`,
{
access_token: useTokenStore.getState().accessToken,
'Content-Type': 'multipart/form-data',
},
[
...fileData,
// elements without property `filename` will be sent as plain text
{name: 'org_id', data: String(org_id)},
{name: 'ans', data: String(userAns)},
{name: 'remark', data: String(userRemark)},
{name: 'img', data: String(userImg)},
],
);

set mobx store in const value in react native

how can i set const value using mobx obeserve data? as i don't know how can i define props here.
export const BASE_URL = base_url_from_mobx
i have some data in this function. From there i will have some confidential data and a base url. This ApiKeys is a native module
ApiKeys.getApiKeys((data)=>{
let secureData = JSON.parse(data)
}
i have an api.js file where i set the interceptor and set the base url like below
const api = axios.create({
baseURL: BASE_URL,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
here BASE_URL is defined and export as const in constants.js file but now i want to set it from the value i have got from the function.
This can be done if i can do like below
const api = axios.create({
// baseURL: BASE_URL,
baseURL: (JSON.parse(AsyncStorage.getItem(SECURE_KEY))).SOHOJ_APP_API_BASE_URL_DEVELOPMENT,
timeout: 10 * 1000,
headers: {
'content-type': 'application/json',
}
});
but it is giving me issue like
how can i do that. my i use to make a request like below using api.js
api
.post('api_end_point',parameters,headers)
.then(response=>{
})
.catch(error =>{
})
thanks
It means that there is some issue with your AsyncStorage.getItem(SECURE_KEY) ,probably it's not a proper json object.do a console.log of AsyncStorage.getItem(SECURE_KEY) and see what value you get.

Problem with PUT request in axios with vue.js

I'm building a smart home application. I have a problem with sending PUT request to my rest api (I building it with flask), but when I try send request it gives me HTTP 400 error (( Uncaught (in promise) Error: Request failed with status code 400 )) . Can you help me?
import axios from 'axios';
export default {
data: function() {
return {
value: 0,
lampName: 'Kitchen',
};
},
mounted () {
axios
.get("http://127.0.0.1:5000/lamp/" + this.$route.params.id)
.then(response => (this.value = response.data))
},
methods: {
updateValue () {
axios
.put('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
{value: this.value},
{headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
}
}
try to add the method field to the form and send it in post way like this
formData.append('_method', 'PUT')
then try to send the data regularly
I think it work like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">
import axios from 'axios';
export default {
data: function() {
return {
value: 0,
lampName: 'Kitchen',
};
},
mounted () {
axios
.get("http://127.0.0.1:5000/lamp/" + this.$route.params.id)
.then(response => (this.value = response.data))
},
methods: {
updateValue () {
let formData = new FormData();
formData.append("value", this.value);
formData.append("lampName", this.lampName);
formData.append('_method', 'PUT');
axios
.post('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
formData
})
}
}
}
</script>
So this is the failing request:
axios
.put('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
{value: this.value},
{headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
I don't know what your server is expecting but you're setting a content-type of application/x-www-form-urlencoded while sending JSON data. It seems likely this mismatch is the cause of your problems. You should be able to see this if you inspect the request in the Network section of your browser's developer tools.
If you need to use application/x-www-form-urlencoded then I suggest reading the axios documentation as you can't just pass in a data object like that:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
In short, you need to build up the body string manually, though there are utilities to make that less onerous.
If you actually want JSON data then just remove the content-type header. Axios should set a suitable content-type for you.
Pass your method as post method and define put in form data formData.append('_method', 'PUT') .
updateValue () {
axios
.post('http://127.0.0.1:5000/lamp/' + this.$route.params.id,
{value: this.value, _method: 'PUT'},
{headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}

Is there a limit in the body of a request to an api in React native?Because i cant send large base64 to server

It says me syntax error: JSON Parse error. unrecognized token '<'
Iam using Fetch to do the request.It let me send short base64 strings i tried so what can i do?
This is my call to the api:
export function uploadPost(post) {
let data = {
body: post.body,
picture: post.picture,
type: post.type,
user: {
_id: post.user._id,
name: post.user.name,
picture: post.user.picture
}
}
var headers = {
'Content-Type': 'application/json',
'Access-Control-Origin': '*'
}
return fetch(URL + "/uploadPost", {
method: "post",
headers: headers,
body: JSON.stringify(data)
})
.then(response => Promise.resolve(response.json()))
.catch(err => {
return Promise.reject(err);
})
}
I finally solved it. The problem was that the response was returning a 413 status and I found out that means payload too large. So I added to my node js express server this lines:
var app = express();
//after
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

Serverless Api Gateway Proxy Lambda with Axios to serve binary files (PDF)?

I am using serverless and axios to "passthrough" a PDF generated by the
stampery api, which needs credentials I do not want to save client-side.
In principle I get the PDF as an arraybuffer from axios, transform the arraybuffer to an buffer, which I then use to create a base64 string, needed by API Gateway binary treatment, which can be "activated" by including the isBase64Encoded: true property in the callback response object.
The following code yields an empty PDF:
const axios = require('axios');
const stamperyClientId = 'xxx';
const stamperySecret = 'xxx';
const stampery = axios.create({
baseURL: 'https://api-prod.stampery.com',
auth: {
username: stamperyClientId,
password: stamperySecret
}
});
module.exports.hello = (event, context, callback) => {
const response = {
statusCode: 200,
headers: {
'Content-Type' : 'application/pdf',
'Content-Disposition': 'inline; filename="certificate.pdf"'
},
isBase64Encoded: true
};
stampery.get(`/stamps/5b2a612680e0190004bcccc8.pdf`, {
responseType: 'arrayBuffer',
})
.then(res => {
const buffer = Buffer.from(res.data)
const base64Str = buffer.toString('base64')
response.body = base64Str
callback(null, response);
})
};
The PDF is retrieved by: `curl https://xxx.execute-api.eu-west-1.amazonaws.com/dev/certificate -o my.pdf -H "Accept: application/pdf"
I tested the setup with fileReadSync, which turned out fine:
module.exports.hello = (event, context, callback) => {
const content = fs.readFileSync("data/sample.pdf");
const response = {
statusCode: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": "inline; filename=\"sample.pdf\""
},
body: content.toString("base64"),
isBase64Encoded: true
};
return callback(null, response);
};
What am I missing? Is this the right way to transform an axios arraybufferinto a base64 string?
P.S. My serverless.yml is given by:
functions:
hello:
handler: handler.hello
events:
- http:
path: certificate.pdf
method: get
package:
include:
- data/sample.pdf
resources:
Resources:
ApiGatewayRestApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: dev-stamper
BinaryMediaTypes:
- "application/pdf" # or whichever ones you need
where I already thought of the necessary binary media types.
Ok... the error was a simple typo. I wrote arraybuffer in camel case arrayBuffer, so Axios returned a string instead of an arraybuffer.
Change this line:
stampery.get(`/stamps/5b2a612680e0190004bcccc8.pdf`, {
responseType: 'arrayBuffer',
})
to
stampery.get(`/stamps/5b2a612680e0190004bcccc8.pdf`, {
responseType: 'arraybuffer',
})
and everything works as a charm...