Why do these two axios post methods have different result - express

After two days of struggling finally i found the solution to fix it, But i'm not sure why it works.
I want to make a request to verify JWT in the server with axios so i did it simple like this
axios.post('http://localhost:5000/auth', {headers: {
Authorization: 'Bearer ' + varToken
}})
But i got undefined Meanwhile when i tried it with Postman it worked fine i got the token in the headers of request.
I googled it all day and asked 3 stack overflow questions they all suggested me to specify { Content-Type: application, Accept: application } But it didn't work.
Today i manage to make it works by setting axios like so
axios({
method: 'post',
url: 'http://localhost:5000/auth',
headers: {
Authorization: 'Bearer ' + varToken
}
})
And it works! So my question is
What is the difference between these two axios config ? the first method which is technically being defined everything same as the second method why do i got undefined from it?
*server code
app.post('/auth', (req, res) => {
console.log(req.headers['authorization'])
});

You're not calling the first one properly. The calling signature for that one is:
axios.post(url[, data[, config]])
The 2nd argument is for data, not for config options. If you're not going to pass any data (usually you would with a post), then you could do:
axios.post('http://localhost:5000/auth', "", {headers: {
Authorization: 'Bearer ' + varToken
}});

Related

Axios request to AEM servlet redirecting to login.html

I have a working servlet that tests properly with Postman, but I can't get the request to execute from the front end. The fact that Postman can execute the servlet with either a Get or a Post tells me the problem is likely with the front-end code.
Does anyone see where the misconfiguration is in this block? The Basic key and cookie are copied from Postman, there is no CORs problem.
const response = await axios.get(url, null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Accept': '*/*',
'Content-type': 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Authorization': 'Basic YWRtaW46YWRtaW4='
},
withCredentials: true,
Cookie: "cq-authoring-mode=TOUCH;",
params: {
path: rootPath,
maxCount: sourceMax
}
}).catch(err => {
console.log(err)
}, () => {
console.log(response)
}).then(res => {
console.log(res)
})
This is most likely the CSRF filter which rejects some requests that don’t contain a CSRF token. By default it checks only POST, PUT and DELETE requests.
It’s weird that it also checks your request, which seems to be a GET. Either your filter is configured differently or you sending a Content-type header – which describes the request body content type – makes axios switch the request from GET to POST (because GETs don’t have a request body and, thus, don’t need to declare their content type).
The CSRF filter can be configured in various ways and can exclude certain requests from filtering by path or user-agent:
You could also request a token from the /libs/granite/csrf/token.json endpoint and then send it along in your request. One way to do this is via the query, as the :cq_csrf_token param.

Bandcamp api: What POST info do you send, when querying the my_bands endpoint?

https://bandcamp.com/developer/account#my_bands
It doesnt say what youre sposta send, as POST, and if you send without a POST or empty array, you get a 'must be POST' error. Their support isnt helping.
I have been able to use their other endpoints, so I know I've got the auth correct.
I send an empty payload to https://bandcamp.com/api/account/1/my_bands, like:
var parameters = {
headers: { Authorization: 'Bearer '+access_token },
method: 'post',
payload: '',
muteHttpExceptions: true // we want to handle exceptions gracefully
};

Http with token in Ionic 4

(Sorry for my bad english) I have to access an api, with a token that they have provided me. My problem is that I don't know how to implement it, after searching and searching, it gives me the following error:
Access to XMLHttpRequest at 'https://www.presupuestoabierto.gob.ar/api/v1/credito' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I pass my code to you, to indicate that it is wrong in the definition of the token (the x instead of the token) and eventually in the CORS policy, thank you very much!
const headers = { 'Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'http://localhost:8100'}
this.http.get<any>('https://www.presupuestoabierto.gob.ar/api/v1/credito', { headers }).subscribe(data => {
this.datos = data.blabla;
})
Headers should pass like this in Ionic- Angular. Make sure that you have a service file.Visit this link to know more about services:
https://angular.io/tutorial/toh-pt4
let headers = new Headers({
'Content-Type' : 'application/json',
'Auth':authvalue
});
return this.http.get(url,options).pipe(map(res => res.json()));

Passing JWT in headers with axios

I've created a small project with a node back-end and react front-end to fetch the data through REST calls. I used Axios library, but when I pass the headers with it I keep getting an error saying:
Failed to load resource: the server responded with a status of 401 (Unauthorized).
I found out two methods and both did not work. They are:
export const getUsersDetails=()=>{
console.log('calling');
return (dispatch) => {
return axios.get('http://localhost:3030/users',{headers: { "Authorization": localStorage.getItem('jwtToken') }}).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
and
axios.defaults.headers.common['Authorization'] = localStorage.getItem('jwtToken');
But When I use postman I am getting the required data from the backend. Any particular reason why I keep getting this Unauthorized error?.
You need to concatenate 'Bearer ' before the token, like this:
axios.defaults.headers.common['Authorization'] =
'Bearer ' + localStorage.getItem('jwtToken');

Vue Resource Cross-site HTTP request

Normally, when I make a jQuery request to a non-local server, it applies Cross-site HTTP request rules and initially sends an OPTIONS request to verify the existence of an endpoint and then it sends the request, i.e.
GET to domain.tld/api/get/user/data/user_id
jQuery works fine, however I would like to use Vue Resource to deal with requests. In my network log, I see only the actual request being made (no OPTIONS request initially), and no data is being received.
Anybody has an idea how to solve this?
Sample Code:
var options = {
headers: {
'Authorization': 'Bearer xxx'
}
};
this.$http.get(config.api.base_url + 'open/cities',[options])
.then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
jquery-request
Solution:
As #Anton mentioned, it's not necessary to have both requests (environment negligible). Not sure what I have changed to make it work, but the request gave me an error. It consisted in setting the headers correctly. Headers should not be passed as options but as a property of http:
this.$http({
root: config.api.base_url + 'open/cities', // url, endpoint
method: 'GET',
headers: {
'Authorization': 'Bearer xxx'
}
}).then(function(response){
console.log('new request');
vm.cities = response;
}, function(error){
console.log('error in .js:');
console.log(error);
});
Thank you guys, it was a team effort :)
Is it a requirement that an additional OPTIONS request is being made? I have created a small (32 LOC) example which works fine and retrieves the data:
https://jsfiddle.net/ct372m7x/2/
As you can see, the data is being loaded from a non-local server. The example is located on jsfiddle.net and the request is made to httpbin.org - this leads to CORS being applied (you can see the Access-Control-Allow-Origin header in the screenshot below).
What you also see is that only the GET request has been executed, no OPTIONS before that.