How to get response headers parameter from Axios get request? - reactjs

I want to read the csrf token from the response header of the axios get request which I am going to send with the axios post request as request header. My code is as below :
const FileApi= {
list: (type:string,period:string): AxiosPromise<FilesL[]> =>
axios.get(`upload/${type}/${period}`)
.then(res=> {console.log(res.headers.get("X-CSRF-TOKEN"))}),
upload: (file:File,type:string,period:string): AxiosPromise<string> => {
return axios.post(`file/upload/${type}/${period}`,form,{
headers :{
'Content-Type':'multipart/form-data',
'token' : X-CSRF-TOKEN,
},
});
}
}
I am not able to get the token from the get request and so the post request is not functioning as the X-CSRF-TOKEN is undefined.

Should just be res.headers['X-CSRF-TOKEN']

Related

How do i enable cors policy / or request in react js with no access to the API?

Im using RapidApi to make som simple calls for fetching country data using axios. The API is paged in that the next response will have the URL for the next request. So basically i don't even have the URLs.
Problem i get the error which i have seen all over stack overflow about cors policy
Access to XMLHttpRequest at 'https://api.hybridgfx.com/api/list-countries-states-cities?page=2' from origin 'http://localhost:3002' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried adding the line "access-control-allow-origin": "*" but that doesn't work and i still get the same error. When i click on the URL or just run it directly on the browser i get a bunch of data but when it is called in the code it blows up . Please help.
const fetchNextResults = async (url: string): Promise<FetchResponse> => {
const options = {
method: "GET",
url: url,
headers: {
"X-RapidAPI-Key": MyKey,
"X-RapidAPI-Host": "countries-states-cities-dataset.p.rapidapi.com",
"access-control-allow-origin": "*",
},
};
const res: FetchResponse = await axios
.request(options)
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.error(error);
});
return res;
};
You can send a request throw the CORS proxy.
List of proxies.
url: <proxy url>/<my url>
Or create your own.

cakephp XMLHttpRequest post request csrf problem

cakephp 4.4.6
I use vuejs as frontend, all works fine, but I have csrf problems to send XMLHttpRequest with post request.
CsrfProtectionMiddleware is activated.
It works fine when post data are send from an html "form" (_csrfToken is in a hidden field).
But if post data are send from an axios request, cakephp backend cannot get the csrf token.
Here is the front code:
axios
.post("/equipes/delete", {
headers: {
"X-Requested-With": "XMLHttpRequest",
'X-CSRF-Token': this.csrftoken,
},
params: {
// csrfToken: this.csrftoken,
// _csrfToken: this.csrftoken,
id: id,
},
})
.then((response) => {
})
.catch((e) => {
console.log(this.$options.name + ": method confirmationDelete : error");
});
The parameters send to the cakephp backend:
And the error returned :
Any ideas ?
Thanks

Post Request from axios always returns Unauthorized despite having valid JWT set in header/Axios Deletes Headers

I set up passport-local to login a user, and then once logged in, the user will be given a JWT token through passport-JWT. The JWTStrategy is set up to use
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() so that the JWT can sent with the Authorization header Authorization: `Token ${userContext.token}`}. In my react client side, I have set up a GET request using axios as shown here:
const fetchProfileDetails = async(config)=>{
const res = await axios.get("http://localhost:8080/users/me", config)
}
const config = {
method:"GET",
withCredentials: true,
headers: {Authorization: `Bearer ${userContext.token}`}
}
This request successfully authenticates and returns the user data from /me.
Now heres the kicker: when I use the exact same request structure, but switch the method to post in the axios request and in my express route in the backend, the request always responds with a 401 Unauthorized.
However, when I send the same request from POSTMAN, with the same Bearer Token used in the request that was Unauthorized, the request succeeds without any errors.
TLDR: GET requests work with the JWT token and return with a 200 status code, while the same request with a POST method returns with a 401 status code.
What am I missing here??!
You are probably using there GET and not using POST anywhere.
In your code, you have code only for get. You will need to write code for post as well.
Below is the code for post for your reference:
router.post('/', config, async(req, res, next) => {
const { error } = validateBody(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
const newData= new passport({ name: req.body.name });
await newData.save();
console.log('saving the document');
res.send(newData);
})
Your code should have post as well. Writing single code will not work. You need to have to write code for every condition and every possibility. So like for get need code for post as well, also if you have condition for patch or delete or put you will have to write the axios method for that as well.
Hope this has helped you in any way.
I have come upon a solution for this issue. For some reason, axios was not maintaining the Authorization header I had set in my config variable, and deleted it upon making the request. To solve this, I just had to reshuffle my axios request to look like this:
const res = await axios({
method:'POST',
url:"http://localhost:8080/users/test",
headers:{'Authorization':`Bearer${token}`
}})
I feel cheated as I spent a ton of time on this and the solution was so underwhelming. Axios was trolling me the whole time :/

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/

I am using react and axios. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

axios. post error.
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
I am using the axios, react and redux.
My code is:
const config = {
method: 'post',
url: addActivityUrl,
data:data,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
},
};
return function (dispatch) {
axios.request(config)
.then(function(response){
dispatch({type:ADD_ACTIVITY_SUCCESS,payload:response.data});
} )
.catch((error)=> {
dispatch({type:ADD_ACTIVITY_ERROR,payload:error});
})
}
}
I set the breakpoint in the error callback function. When I send a post request,the error above will show me.
I looked for the answer on Stack Overflow. I don't found the answer yet.
I don't know the reason.
Most you have an issue with custom request headers.
When using custom request header you will get a CORS preflight. This type of request use HTTP OPTIONS and includes Access-Control-Request-Headers listing the headers the client wants to include in the request.
Your client code need to reply to CORS preflight with the appropriate CORS headers. That header needs to contain the same values the Access-Control-Request-Headers.

Resources