How to get access to cookies in react js - reactjs

How to get access to cookies that I get in the response of axios post and get request, Am using WooCommerce Rest API and I need the access to PHPSESSID that I get on response, I tried on postman as it automatically set the cookie to header, Is there anyway to do in React JS?

The fetch API allows you to read the response headers of a request:
const getResponse = async () => {
const response = await fetch("https://stackoverflow.com/");
// log all response headers
console.log([...response.headers.entries()])
// look for set-cookie
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
console.log(response.headers.get("set-cookie"));
}
However this will only work if the WooCommerce Rest API will set or modify the cookie exactly in that response.

Related

Django server unable to get data from react Axios

I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue!
My react axios request
// PrivateAxios instance to send api request
const axiosPrivate = useAxiosPrivate();
const handleSearch = async () => {
const data = JSON.stringify({ from_company: keyWord });
try {
const response = await axiosPrivate.get(SEARCH_URL, data);
console.log(response);
setRecords(response?.data);
} catch (err) {
if (!err?.response) {
console.log("NO SERVER RESPONSE");
} else {
console.log("SOMETHING WRONG");
}
}
};
Server log
{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276
The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app.
Request sent from Postman returns
{'from_company': 'Jethmal Paliwal'} <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284
I have double checked everything, my headers are set correctly, Content-Type: application/json, withCredentials: true, and every other possible settings, Even every request from other components works great, but why this particular request doesn't reach the server?
Tried writing the data as an Object in the request funcion itself
const response = axiosPrivate.get(SEARCH_URL, { "from_company": "Jethmal Paliwal" }); which doesn't work as well. The same empty object gets printed.
Tried JSON.stringify the data, which doesn't work as well.
I believe that axios is omitting the data as it's not per REST standard to submit data in the GET request. HTTP allows that, but people and apparently libraries are not expecting it.
This is the API for axios get method:
axios.get(url[, config])
as you see there is no data in the method signature. And if we look at the POST method:
axios.post(url[, data[, config]])
I suggest if you have data to submit to server that you use a POST method instead.

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 :/

HERE Geocoding API - not working inside my React app

I have a React app in which I use the HERE Geocoding API. I have an axios request to retrieve latitude and longitude and it does not work as well as expected. The request is not working inside my app
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`)
I have a 401 error. Bearer token invalid. Bearer missing or bearer value missing. If I open a new tab in my browser and paste the url https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey it works fine and I get the result I need.
I tried using the Authorization header
const config = {
headers: {
'Accept': 'application/json',
'Authorization': `apiKey myAPIKey`,
}
};
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=myAPIKey`,config)
In the Authorization header, I tried with Bearer and Basic instead of apiKey
documentation HERE API
In the documentation about how to create an API Key and how to use it, the only thing I need to do is what I have already done. I have created a project, an API Key and I use it in my request.
HERE Geocoding API Key
I don't know how the HERE api works but the error message is probably the answer you are looking for.
You are likely to provide the api key via the Authorization header with your request. Read about the header on MDN
You just need to pass your API key in the link as a parameter.
Just sign up and you can get your API key.
https://developer.here.com/sign-up
The code should be like this.
return axios.get(`https://geocode.search.hereapi.com/v1/geocode?q=${address}&apiKey=${HERE_MAP_API_KEY}`,config)
The latest request would look like this.
axios.get(`https://geocoder.ls.hereapi.com/search/6.2/geocode.json?languages=en-US&maxresults=${maxResults}&searchtext=${query}&apiKey=${HERE_MAP_API_KEY}`)
.then(res => {
const data = res.data
console.log(data)
})
.catch(err => console.log(err))

Get cookie/localStorage value in nextjs API request

I'm trying to get cookie or localStorage value in my API request. When I'm trying to access localStorage I get error that localStorage is not defined, cookies are undefined, I tried my luck with AsyncLocalStorage, but I'm getting error that window is undefined. There is any way to get saved value in this asynchronous function?
import AsyncLocalStorage from '#createnextapp/async-local-storage'
export default async (req, res) => {
try {
let data = await AsyncLocalStorage.getItem('#key')
console.log(data)
}catch(error){
console.log(error)
}
}
This is expected. When you process the data in your API it is actually running in the server. Localstorage, and cookies however are browser based storage (This is also why window is undefined, servers don't have windows). As a result they are not available to the API to leverage. Instead when you make the API request you need to add the data into a header which can then be parsed on your server.
Setting a header on your request:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
From there you should be able to read the headers through:
(req, res) => {
// look at all these great headers we have
const { headers } = req;
}

Cookie not setting in Scala Play

I am trying to set a cookie from a response when using the scala play framework. I am creating a cookie called session with its value being a UUID (I do know play comes with its own session management).
I can see the response headers contain the set cookie instruction, but the cookie ins't being set.
Below is the scala code in the action in the controller where the cookie is set
val cookie= Cookie("session",
sessionToken,
httpOnly=true,
sameSite=Some(Cookie.SameSite.Lax))
Ok(Json.toJson(res))
.withCookies(cookie)
// Also tried with .bakeCookies() after the withCookies() call
I can see the cookie header in the response in both FireFox and Chrome. They both show what appears to be a correctly formed cookie in their respective response cookie viewer in their developer tools.
Set-Cookie: session=c0174ed1-ebd3-4a8d-a5b2-5b09a3fe616b; SameSite=Lax; Path=/; HTTPOnly
However, in both browsers the cookie does not get set. I have tried true and false httpOnly, and messing with the maxAge value. I have tried setting the domain to a url and then setting the url in the hosts file as suggested here.
The URL on the react frontend is
http://localhost:49161/login/hydrate
and the endpoint in play is
http://localhost:49162/user/login/rehydrate
I did also try setting the path to /login/hydrate/ on the cookie
The react code on the front end
// Inside async function
// methodStrings[method] = "post" in this request
axios[methodStrings[method]](url, params)
.then(result => {
resolve(result);
})
.catch(err => {
console.error(`Error with request to ${url} - ${err}`);
reject(err.response.status);
});
And then I console.log the result from awaiting the request
Problem is in axios (and/or browser).
Based on this issue Cookies headers are present but Cookies are not stored in browser #1553 you need to set withCredentials Axios config to store cookies in browser after request:
axios.post('domain.com', {
name: 'name',
password: 'password'
}, {
//AxiosRequestConfig parameter
withCredentials: true //correct
})

Resources