How to Send Authentication Token Header with DropzoneJs? - javascript

I am having a problem sending an authorization header with dropzonejs
this.componentConfig = {
iconFiletypes: ['.jpg', '.png', '.gif'],
showFiletypeIcon: true,
postUrl: `${getBaseUrl()}/Controller/ImportImage`,
headers: {
'Authorization': 'Bearer'
},
};
<DropzoneComponent config={config} eventHandlers={eventHandlers} djsConfig={djsConfig}> </DropzoneComponent>

Based on the code the headers are define like:
var headers = {
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest"
};
So, defining like
headers: { "Authorization" : "Bearer AbCdEf123456" }
should work.

Related

how to call API from axios with header

I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results
and the body request looks :
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
})
.then((response) => {
if (response.status !== 200) {
return res.send(respone("500", response.data.result.data))
} else {
return res.send(respone("200", response.data.result.data))
}
})
.catch((error) => {
console.log(error);
return res.send(error)
})
the error show
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Content-Transfer-Encoding": "application/json",
"HTTP_API_KEY": "xxxx",
"User-Agent": "axios/0.27.2",
"Content-Length": 2
},
"method": "post",
"url": "xxxxx",
"data": "{}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}
It seems you nested your headers inside another "headers" property.
Basically you're doing this
headers: {
headers: {
'Content-Transfer-Encoding': ...
}
}
As Zai showed in her answer you problem is your header variable:
const header = {
headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
}
is nested, when you do this:
axios({
method: 'POST',
url: URL,
headers: header,
data : {
}
what you are really doing is:
axios({
method: 'POST',
url: URL,
headers: headers: {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
},
data : {
}
So your header: instead of being Content-transfer etc... is just 'headers'
try this:
const header = {
'Content-Transfer-Encoding': 'application/json',
'content-type': 'application/json',
'HTTP_API_KEY': 'xxxxx',
}
also, i recommend you to do a console.log with your api call in order to find this problems faster and compare with postman, really helpful in develop phase (just use it in local, never push that log to production)

How can I include authorization Headers in my react-app?

On postman, I can access endpoints by adding the headers:
Key: Value ( I will insert fake figures for example)
x-mash-auth-token: gdjsjaosh-hkds-dhjsk-hjjdbahsj
I am building a react app that allows user to search endpoints, how can I include this header in my code to grant user access on UI?
axios({
url: "API URL",
method: "GET",
data: {name: "abc"},
contentType: 'application/json',
headers: {
"Access-Control-Allow-Origin": "*",
'Accept': 'application/json',
'Content-Type': 'application/json',
'Pragma': 'no-cache',
'Authorization': 'Bearer gdjsjaosh-hkds-dhjsk-hjjdbahsj',
'Access-Control-Expose-Headers': "jwt_token"
},
responseType: 'json'
})
.then(function (response) {
successCallback(response);
})
.catch(function (error) {
errorCallback(error);
})

How to fix sending headers with axios post?

I use axios to send a POST HTTP request with some binary data like this:
axios.post(url, input, {headers: {'Content-Type': 'application/octet-stream'}})
When I got an Bad request error I printed out the request headers:
"headers" : {
"common": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/octet-stream"
},
"delete": {},
"get": {},
"head": {},
"post": {
"Content-Type": "application/octet-stream"
},
"put": {
"Content-Type": "application/x-www-form-urlencoded"
},
"patch": {
"Content-Type": "application/x-www-form-urlencoded"
}
}
I overrode the default headers (see below) and got Ok instead Bad request
axios.defaults.headers = {"Content-Type": "application/octet-stream"}
So the problem is fixed but I don't like overriding axios defaults. How would you suggest use axios.post to send the header correctly ?

how to handle request header accept application/ld+json in react.js get request

how to handle request header accept application/ld+json in react.js get request
Media type
application/id+json
Controls Accept header.
i am getting unauthorized 401 error dont know why can anyone please explain me i am facing this type of error for the first time .
function parseJwt(token) {
if (!token) { return; }
const base64Url = token.split('.')[1];
const base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse(window.atob(base64));
}
export async function getRequest(url , token){
let token_data = parseJwt(token)
console.log('Token data ', token_data)
let response = await fetch(API_URL(url), {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": `application/${token_data.id}+json`,
// 'Content-Type': `application/${token_data.id}+json`,
// "Authorization": JSON.stringify(token_data)
},
redirect: "follow",
referrer: "no-referrer",
})
return response
}
Please Try Below code
var token = 'XXXXX-XXXX-XXXXX';
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': token
},
body: payLoad,
})

Different headers for post and get request with axios,create?

export default myAPI = axios.create({
baseURL: 'myapiurl',
// headers for post reuqest
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
'X-CSRF-TOKEN': 'o987WyyzM7ktyEVzP4dakCdIY12LprtJU8qZHs5Xs0s',
},
// headers for get requests
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
Basically want conditional headers depending on weather a post or a get request is being made.
You can use different headers based on HTTP method in this way:
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
As explained here: https://github.com/axios/axios#global-axios-defaults

Categories

Resources