I am working with React Hooks and I want to use the axios hooks package to send an image to Cloudinary.
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT'
},
{ manual: true }
)
The docs say nothing about headers?
I believe you are looking for this:
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://api.myjson.com/bins/820fc',
method: 'PUT',
headers: {
'Content-Type': 'application/json'
}
},
{ manual: true }
)
docs: https://github.com/axios/axios#request-config
Related
Maybe it's duplicated anyway i've searched this specific case without finding anything related.
I'm working to plot a chart with tradingview and bitquery api using axios and graphql
The config of my query goes like this:
Bitquery.endpoint, {
query: Bitquery.GET_COIN_INFO,
variables: {
"tokenAddress": symbolName
},
mode: 'cors',
headers: {
"Content-Type": "application/json",
"X-API-KEY": "XXXXXXXXXXX",
"Access-Control-Allow-Origin" : "http://localhost:3000",
"Access-Control-Allow-Credentials" : "true",
"Access-Control-Allow-Methods" :" GET, POST, OPTIONS",
"Access-Control-Allow-Headers" : "Origin, Content-Type, Accept"
}
}
);
But i still receiving this error on console:
Access to XMLHttpRequest at 'https://graphql.bitquery.io/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Could someone give me a hint upon this? Thank you!
This query did worked:
const response = await fetch(
Bitquery.endpoint, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-API-KEY": "XXXXXXXXXXXXXXXXXXXXXX"
},
variables: {
"tokenAddress": symbolName
},
mode: 'cors',
body: JSON.stringify({
query:`
{
ethereum(network: bsc) {
dexTrades(
options: {desc: ["block.height", "transaction.index"], limit: 1}
exchangeAddress: {is: "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73"}
baseCurrency: {is: "0xe87e15b9c7d989474cb6d8c56b3db4efad5b21e8"}
quoteCurrency: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}
)
{
block {
height
timestamp {
time(format: "%Y-%m-%d %H:%M:%S")
}
}
transaction {
index
}
baseCurrency {
name
symbol
decimals
}
quotePrice
}
}
}
`
})
}
)
.then((res) => res.json())
.then((result) => {return result})
// const coin = response.data.data.ethereum.dexTrades[0].baseCurrency;
// console.log(response.data.data.ethereum.dexTrades[0].quotePrice);
console.log(response);
I want to fetch an API
The call look like this;
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
headers: {
"Content-Type": "application/json",
},
});
The API spec https://compound.finance/docs/api
{
"addresses": [] // returns all accounts if empty or not included
"block_number": 0 // returns latest if given 0
"max_health": { "value": "10.0" }
"min_borrow_value_in_eth": { "value": "0.002" }
"page_number": 1
"page_size": 10
}
However the output URI contains some character to replace { } arround max_health value
The uri end up looking like this;
/api/v2/account?block_number=0&page_number=1&page_size=250&max_health=%7B%22value%22:%221%22%7D'
I have tried qs but it's not working as I expect.
I have tryed this to ;
let params = {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
}
}
await instance.get('https://api.compound.finance/api/v2/account',JSON.stringify(params)).then( (response) => {...})
It gave me this error ;
TypeError: Cannot use 'in' operator to search for 'validateStatus' in
{"block_number":"0","page_number":"1","page_size":"250","max_health":{"value":"1"}}
Any help would be appreciated.
The fix;
Use paramSerializer
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
headers: {
"Content-Type": "application/json",
},
});
I want to access the $auth object in the context from the js defined under 'plugins/', but I can't.
https://auth.nuxtjs.org/api/auth.html#auth
This module globally injects $auth instance, meaning that you can access it anywhere using this.$auth. For plugins, asyncData, fetch, nuxtServerInit and Middleware, you can access it from context.$auth
It is described above, but my code (axios-interceptor.js) cannot access $auth from context (it is undefined).
What does it take to be able to access it?
plugins/axios-interceptor.js
export default function (context) {
const { $axios, route, redirect } = context
$axios.interceptors.response.use(
function (response) {
return response
},
function (error) {
const code = parseInt(error.response && error.response.status)
const thisRoutePath = route.path
if ([401, 403].includes(code)) {
if (thisRoutePath !== '/') {
redirect('/?login')
}
}
return Promise.reject(error)
}
)
}
nuxt.config.js
export default {
plugins: [
'#/plugins/axios-interceptor.js'
],
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy',
'#nuxtjs/auth'
],
axios: {
baseURL: BASE_URL
},
auth: {
cookie: false,
autoFetchUser: false,
redirect: {
login: '/login',
logout: '/login',
callback: '/callback',
home: '/home'
},
strategies: {
local: {
endpoints: {
login: { url: BACKEND_API_PATH_BASE + '/api/v1/login/', method: 'post', propertyName: 'token' },
user: { url: BACKEND_API_PATH_BASE + '/api/v1/users/me', method: 'get', propertyName: false },
logout: false
},
},
}
},
router: {
middleware: [
'auth'
]
},
The reason I want to access $auth in axios-interceptor.js is that I want to execute $auth.logout() in the if ([401, 403].includes(code)) { block and remove the token.
I am now able to access $auth by doing the following
export default {
// plugins: [
// '#/plugins/axios-interceptor.js' ########### REMOVE ###########
// ],
:
(Ommit)
:
auth: {
:
(Ommit)
:
plugins: [
'#/plugins/axios-interceptor.js' // ########### ADD ###########
]
},
(Ommit)
:
}
The things I needed to do were listed below.
https://auth.nuxtjs.org/recipes/extend.html
I want to host on a private website the documentation of my swagger API using swagger-ui.
The YAML file is hosted on a private GitHub repository. According the this gist, I successfully retrieved the desired file with the curl command line but I'm stuck trying it with swagger-ui:
window.swaggerUi = new SwaggerUi({
url: 'https://api.github.com/repos/me/my_repo/contents/api.yaml',
authorizations: {
'Authorization': 'token 0123456789',
'Accept': 'application/vnd.github.v3.raw'
},
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
if(typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: ",",
additionalQueryStringParams: {}
});
}
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
jsonEditor: false,
defaultModelRendering: 'schema',
showRequestHeaders: false
});
window.swaggerUi.load();
I get an error:
http.js:296 Uncaught TypeError: auth.apply is not a function
Any suggestions?
Here is the answer: (Note that it doesn't work with YAML file. Only JSON.)
// spec: content,
window.swaggerUi = new SwaggerUi({
url: 'https://api.github.com/repos/me/my_repo/contents/api.json',
authorizations: {
'Accept': new window.SwaggerClient.ApiKeyAuthorization("Accept", "application/vnd.github.v3.raw", "header"),
'Authorization': new window.SwaggerClient.ApiKeyAuthorization("Authorization", "token 0123456789", "header"),
},
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
if(typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: ",",
additionalQueryStringParams: {}
});
}
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
},
onFailure: function(data) {
log("Unable to Load SwaggerUI : ", data);
},
docExpansion: "none",
jsonEditor: false,
defaultModelRendering: 'schema',
showRequestHeaders: false,
});
Here's my code:
var userAuth;
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
userAuth = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: {
'Authorization': userAuth
}
}
});
I want to be able to use the updated contents of the userAuth variable in the headers of the current endpoint of the resource, after it has been modified in the transformResponse of the login call. Is this even possible? If so, how?
EDIT: I am using Angular version 1.1.3 - this question is about changing the headers in the resource once they have been set, not settings them initially. Thanks
Assuming you are using the current stable release (1.0.8), although this feature is documented in the $resource page it has not been released.
AngularJS resource not setting Content-Type
EDIT:
See my comment below for the explaination of this code.
var customerHeaders = {
'Authorization' : ''
};
var user = $resource('https://myservice.com/user/:id/', {id: '#_id'} ,{
login: {
method: 'POST',
params: {
id: 'login'
},
transformResponse: function(data) {
data = angular.fromJson(data);
customHeaders.Authorization = 'Kinvey '+data._kmd.authtoken;
return data;
}
},
current: {
method: 'GET',
params: {
id: '_me'
},
headers: customHeaders
}
});