Auth header not being set with Axios PUT request - reactjs

I am trying to set the header in an Axios PUT request with my Auth token, but when I view the call on the server (running my UI app from localhost) the header is null. I've used this same pattern with Axios and GET, POST, and DELETE calls without issue. Is there anything different with respect to a PUT call and the header?
Below is the code:
return axios.put(BASE_URI + '/submissions/' + submissionId + '/submit',
{
headers: {
'Authorization': 'Bearer ' + this.accessToken,
}
})

In order to add headers in POST or PUT, you need a third argument which will contain headers keys
axios.put(url, data, config)
return axios.put(BASE_URI + '/submissions/' + submissionId + '/submit',
{}, // post/put body
{
headers: {
'Authorization': 'Bearer ' + this.accessToken,
}
})

Related

Axios post spotify api request return 400

I am using spotify api for a project. Every request I made work fine except this one. I want to be able to create a new playlist. The scope was already checked, it's not the source of the problem. For this I made the following request
axios('https://api.spotify.com/v1/users/' + ID + '/playlists', {
method: 'POST',
headers: {
'Authorization' : 'Bearer ' + data.data.access_token,
"Content-Type" : "application/json"
},
data: {
name: Name,
Description: Description
}
})
when I tried it, I've got 400 Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information
Here's the link for the spotify api references
https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/
assuming your ID is defined. You need to stringify your json.
Been a while since I used axios,
axios('https://api.spotify.com/v1/users/' + ID + '/playlists', {
method: 'POST',
headers: {
'Authorization' : 'Bearer ' + data.data.access_token,
'Content-Type': 'application/json'
},
data: JSON.stringify({
name: Name,
description: Description
})
})

PostMan vs Axios on Including authorization Header while Making requests

Making a postman request to an endpoint with some Header
when I run the below code
function authenticateToken(req,res,next){
const bearerHeader = req.headers["authorization"]
console.log(req.headers)
if(typeof bearerHeader !== 'undefined'){
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
}
else{
console.log('hihihi')
res.sendStatus(403);
}
}//a middleware function used for JWT
it's returning everything as I expected like below
but the problem is, I need to connect it with my react. So I am making Axios request but it's not working
I tried giving headers using interceptors like below
axios.interceptors.request.use(
config=>{
config.headers.authorization = `Bearer ${token}`
return config
},
error =>{
return Promise.reject(error)
return error
}
)
axios.post("http://localhost:3000/stockdata/post",{
// some data
})
I also tried giving like below
axios.post(url,{data},{headers:{
'authorization': "Bearer "+ token,
'Accept': 'application/json',
'Content-Type': 'application/json'
})
i also tried with 'Authorization': "Bearer "+ token and without quotes Authorization: "Bearer "+token and also tried one time by removing Accept and content-type . but this is what am getting
The problem is only with the Axios request, not any other thing. what's going wrong in it?
I think when you tried with axios, there will be two requests as it has CORS issue. This issue comes if the client host is different from server host.
The first request is type OPTIONS to know whether to allow the POST or not and second request is actual POST.
What you are seeing might be of request type OPTIONS. This you can verify by checking network tab in the browser. This won't happen in POSTMAN. You could add CORS plugin to your server to resolve this issue.
The attached screenshot shows POSTMAN sending request to http://localhost:3000/stockdata/post
However, the axios request is being sent to http://localhost:3000/stockdata
Adjusting the request end-point may help resolve the issue.
After adjusting the target URL, the following code example may be tried to get the axios response:
import axios from 'axios'
let url = "http://localhost:3000/stockdata/post"
let data = {}
let token = "xyz"
let config = {"headers": {
"Authorization": "Bearer " + token,
"content-type": "application/json"
}
}
axios.post(url, data, config)
.then((response) => {
console.log(response)
}, (error) => {
console.log(error)
}
)
More information:
https://blog.logrocket.com/how-to-make-http-requests-like-a-pro-with-axios/

How to pass JsonWebToken(JWT) through AngularJS

I created a Django RESTful API with JWT as authentication method, but unable to pass the token as headers using angularJS.
I think there is no error on my API, since I used the token I acquired by this script and tested it in Postman:
my JWT token authentication script is here:
// Uses http.get() to load data from a single API endpoint
list() {
return this.http.get('api/', this.getHttpOptions());
}
// helper function to build the HTTP headers
getHttpOptions() {
return {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
})
};
}
I tried using http.get() here. Thanks in advance!
the error will be like:
401 (Unauthorized)
Try this:
list() {
return this.http.get('api/', { this.getHttpOptions() });
}
getHttpOptions() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
});
return headers;
}
Same issue on JWT for CakePHP3, and follow header slove it, may it is helpful.
this.http.get('api/', { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token,
'Authenticationtoken': 'JWT ' + this._userService.token
}) });
Thanks guys,
I found the problem is about CORS, My solutions are here, there are two approaches to solve this problem, one is add 'Access-Control-Allow-Origin': '*' to your http request, sometimes you need add more. Another answer is add CORS_ORIGIN_WHITELIST = 'localhost:4200', in your backend.
https://www.youtube.com/watch?v=OIbndrrUYiY

Can not add bearer token in $resource header

I am not able to add bearer token in $resource service header for token based authentication. I used following code
Factory
return $resource(appSettings.serverPath + "/api/product/:id", null, {
'get': {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + currentUser.getProfile().token
}
}
Also i tried below code as per some research in app.run
$http.defaults.headers.common.Authorization = 'Bearer ' + currentUser.getProfile().token;
But both options do not add this header in my request and i can see request in chrome without this headers and hence got unauthorized response. I am using angular 1.5.9. Any clue on this.
Assuming currentUser is a service and currentUser.getProfile() is a synchronous API:
app.factory("myRestAPI", function(currentUser) {
return $resource(appSettings.serverPath + "/api/product/:id", null, {
'get': {
method: 'GET',
headers: {
//REPLACE expression
//'Authorization': 'Bearer ' + currentUser.getProfile().token
//WITH a function
'Authorization':
function() {
return 'Bearer ' + currentUser.getProfile().token;
}
}
}
);
});
By using a function instead of an expression, the Authorization header will be computed on every call.
From the Docs:1
headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.

$http.post send Authorization Header

I am attempting to pass an Authorization Header with a $http.post call to a .NET Web API service.
If I use this :
$http.post(urls.getEmployeeInfo,
{
withCredentials: true,
headers:{ 'Authorization': 'Basic ' + btoa(username + ":" + password)}
}
);
The Authorization header does not get sent to my service.
The following works :
$http({
url: urls.getEmployeeInfo,
method: "POST",
withCredentials: true,
headers: {
'Authorization': 'Basic ' + btoa(username + ":" + password)
}
});
Why doesn't $http.post send the Authorization Header ?
Thanks
$http takes only one argument: config [documentation]
$http.post takes three arguments: url, data, (and an optional) config [documentation]
So if you want to pass configuration options, such as headers, you need to send them as the third argument, rather than the second:
$http.post(urls.getEmployeeInfo, postData,
{
withCredentials: true,
headers:{ 'Authorization': 'Basic ' + btoa(username + ":" + password)}
}
);

Resources