Using axios I want to send a request with X-Auth-Token in header.
Which one is the correct solution for doing this:
const url = `https:/.../${sku_id}/tokens/${token}`;
const result = await axios.post(url, { headers: { 'X-Auth-Token': token } });
Or this one:
const result = await axios.post(url, { headers: { 'Authorization': `token ${token}` } });
Related
I have a problem in my authentication.js file where for some reason it can't access the token from the header but I have checked that I passed it on the front end. I also used postman and everything seems to work fine so I am sure that the problem is in the authentication.js file where when I try to console.log the token it's undefined.Below is the code:
const token = localStorage.getItem("token");
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
const token = req.get("authorization");
console.log(token); // Logs the token as undefined
if (!token || token === "") {
req.isAuth = false;
return next();
}
try {
let decoded = jwt.verify(token, process.env.JWT_SECRET);
req.duser = decoded.user;
res.status(200).send("Access granted.");
} catch (error) {
return res.status(403).send("Token is not valid.");
}
req.isAuth = true;
return next();
};
Also here is how I call the API:
const token = localStorage.getItem("token");
const { data } = await axios.post(
"/messages",
{
headers: {
Authorization: token
},
}
);
Please change this
headers: { Authorization: token },
to this
headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
in your api call
Do not forget to add data param as the second param. It's your request body.
axios
.post(
`/messages`,
data,
{
headers: {
"Authorization": `Bearer ${token}`, //mind the space before your token
"Content-Type": "application/json"
}
}
);
e.x. data
{
"firstname": "Firat",
"lastname": "Keler"
}
And then in the backend, check your token like that
const token = req.headers.authorization.split(' ')[1];
if (!token) {
//your logic
}
may be that your token isnt a Base64 String via client-side. Hope this helps
const temp = localStorage.getItem("token");
const token = Buffer.from(tmp, 'utf8').toString('base64')
axios.post('/messages', {
headers: {
'Authorization': `Basic ${token}`
}
});
RESOURCE:
https://flaviocopes.com/axios-send-authorization-header/
When i create header object and pass it , it is not working, it is not even hitting the server
const post = async (url, request) => {
let testHeader = new Headers();
testHeader.append('Accept', 'application/json');
testHeader.append('Content-Type', 'application/json');
const response = await fetch(url,
{
method: 'POST',
credentials: 'same-origin',
headers: testHeader,
body: JSON.stringify(request)
}
);
return responseHandler(request, response);
};
but when i pass the headers like this , it works with out any issues
const post = async (url, request) => {
const response = await fetch(url,
{
method: 'POST',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(request)
}
);
return responseHandler(request, response);
};
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,
})
I'm trying to make an API request using fetch(browser). A token is required in the headers to make the request.
I can make successful requests in node (server side).
However, when making requests on the browser, the OPTIONS request fails with 401.
const order_url = new URL(process.env.API_URL + 'orders/');
const params = { type: 'amazon', status: 'in_queue' };
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
const headers = {
Authorization: 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
};
fetch(order_url, {
headers
})
.then(response => response.json())
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error)
})
The error i receive is "NetworkError when attempting to fetch resource."
What would be the correct configuration for this to work on the browser?
You are not sending headers properly.
Try this.
myHeaders = new Headers({
'Authorization': 'Token ' + process.env.API_TOKEN,
'Content-Type': 'application/x-www-form-urlencoded'
});
and then
fetch(order_url, {
headers: myHeaders,
method: 'GET'
})
I'm trying to write a Post method with Axios in NodeJS.
I have following things to pass as param in post method
url = http:/xyz/oauthToken
header 'authorization: Basic kdbvkjhdkhdskhjkjkv='\
header 'cache-control:no-cache'
header 'content-type: application/x-www-form-urlencoded'
data 'grant_type=password&username=user123&password=password123'
As I tried with following code but new to Axioz not sure how can exactly implement the header with grant type of body response.
var config = {
headers: {'Authorization': "bearer " + token}
};
var bodyParameters = {
data 'grant_type=password&username=user123&password=password123'
}
Axios.post(
'http:/xyz/oauthToken',
bodyParameters,
config
).then((response) => {
console.log(response)
}).catch((error) => {
console.log(error)
});
Any help/suggestion would be appreciated :-)
Currently, axios does not make it convenient to use form-encoded data; it's mostly optimized toward JSON. It's possible, though, as documented here.
const querystring = require('querystring');
const body = querystring.stringify({
grant_type: 'password',
username: 'user123',
password: 'password123'
});
axios.post('http:/xyz/oauthToken', body, {
headers: {
authorization: `bearer ${token}`,
'content-type': 'application/x-www-form-urlencoded'
}
});