Why is axios cookie undefined? - node.js

When I try to hit an endpoint with postman everything works, so I assume the problem is probably with my axios request as when logging req.headers.cookies on server after performing this axios request the value is undefined.
Cookies in browser work as well they are set correctly.
When i performed this request in postman the value of req.headers.cookie was fine and the request has been performed without any errors.
Client code:
useEffect(() => {
(async () => {
const res = await axios.post('http://localhost:4000/refresh_token', {
withCredentials: true,
});
})();
}, []);
Server code (endpoint function):
export const validateRefreshToken = async (req, res) => {
console.log(req.headers.cookie); // undefined
const { token } = parse(req.headers.cookie);
...
};
Error message: TypeError argument str must be a string.
This error points to the parse function.
Has anyone experienced this before? Any ides on how I can fix this issue?

With Axios POST, 1st arg is the url, 2nd arg is data and the 3rd arg is for options.
Provide withCredentials: true in the 3rd argument of Axios.post
useEffect(() => {
(async () => {
const res = await axios.post('http://localhost:4000/refresh_token', {} ,{
withCredentials: true,
});
})();
}, []);

Related

Node fetchi request using axios returns gibberish data as response

I am a beginner in node and I am trying to consume an API,but response returns gibberish data.I have tested the API routes and I am sure the problem is my request but I clearly cannot tell where.I think I am making an obvious mistake but it is hard to tell.
Here is the function to generate the token
const generateToken = async (req, res, next) => {
const secret = proces.env.MPESA_CONSUMER_SECRET;
const consumer = process.env.MPESA_CONSUMER_KEY;
const auth = new Buffer.from(`${consumer}:${secret}`).toString("base64");
await axios
.get(
"https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials",
{
headers: {
authorization: `Basic ${auth}`,
},
}
)
.then((response) => {
console.log(response);
// token = response.data.access_token;
next();
})
.catch((err) => {
console.log(err);
//res.status(400).json(err.message)
});
};
app.get("/token", (req, res) => {
generateToken();
});
the response I get after console.log is this
data: '\x1F�\b\x00\x00\x00\x00\x00\x00���R#\x02J��ɩ���%�٩yJV\n' +
'J��.�EU�\x1E��Y�N)%IQ\x01\x05\x16���&N�f\x01J:�zS+\n' +
'2�R��3�:�M--��\n' +
'j�,\x00�H��q\x00\x00\x00'
}
Anyhelp to even help me understand where the problem could be will be highly apprecited.
In v1.2.1 fixed this error.
Try it after install axios(v1.2.1) again
Downgrading to Axios version 1.1.3 worked for me
If you are using an older version of axios v1.2.1 should fix the issue

axios get res.data = null

I've had a blockage since last night and I still don't understand, let me explain.
I use React, Mongo DB, and NodeJs, and axios for my API calls
I created a route to retrieve the info of a user, when I test the route with PostMan, I have the user info so everything works as it should, only when I make the api call from my front, my res.data returns "null", so I think it's coming from my api call, but I can't find what's wrong.
I am attaching some screenshot, thank you in advance:
API call :
function Post() {
axios({
method: "get", url: "http://localhost:4000/api/auth", credentials: true,
params: {
userId: "62f045f5253a960077a8ff3f"
}
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
Function back getOneUser:
exports.getOneUser = (req, res, next) => {
userModel.findOne({_id: req.params.userId}).select('-password -email')
.then(post => res.status(200).json(post))
.catch(error => res.status(404).json({error}))
}
In express, use req.query instead of req.params.
This post might clarify the differences between them

React state not updating after a post request?

I'm trying to send a post request to my backend with axios, and my backend gets the values with no problem, but I want to set a state of (sent) to true when the post request is "successfully sent", I put the setSent(true) in the .then() after the axios request. but when I send the request the state isn't updated! what could be the problem? backend gets the values and works fine though... see code bellow:
const submitHandler = () => {
axios
.post(
"/sendFeedback",
qs.stringify({
name,
email,
text,
})
)
.then(() => {
setSent(true) // doesn't work (the state is still false)
})
.catch((err) => {
err && setError(true) // works just fine!
})
}
try
const submitHandler = async () => await axios ...
because it's asynchronous process and returns a promise.

how to write tests for get requests in jest

I am testing API'S with JEST. I don't understand how I'm going to pass values to parameters in GET request.
describe("Refresh Token", () => {
it("Refresh Token", async() => {
const response = await request(app).get("/refreshtoken");
expect(response.status).toEqual(200);
expect(response.body.data).toEqual("hd$snndm12cdj2#Efvvxv");
});
})
In the above case, the output is expected as the given string. But the output is undefined. Besides that what I should do if I have multiple parameters. Below code is my post request code which is working perfectly. I want to pass multiple parameters as I defined in the post request.
describe('Set Profile Image', () => {
it('Set Profile Image', async() => {
const res = await request(app)
.post('/setProfileImage')
.send({
profileID: "1234",
profileImage: "fnsdjnfsnf"
})
expect(res.status).toBe(200)
})
});
Try passing the params in the URL of your request:
const response = await request(app).get("/refreshtoken?param1=123")
To pass multiple parameters, just do this:
const response = await request(app).get("/refreshtoken?param1=123&param2=234")

Using Node and Express, How to Call remote API from inside server.get(..)

Because of CORS problems, I want to call an external REST API from inside my node express server. That is, I have code like this that obviously does not work because it does not return.
How can I make this work and return the results of my external call?
const server = express();
server.put('/callme',(req,res) => {
axios
('http://weather.com/restapi', 'put', { zip: 10530 })
.then((resp: any) => {
console.log(' success' + resp.data);
})
.catch(function(error: any) {
console.log(error.message);
});
}
Axios returns a Promise which is resolved in the .then(). In order to get the response data back to the client you need to return it with res.send().
const server = express();
server.get('/callme', (req, res) => {
axios
.get('http://weather.com/restapi?zip=10530')
.then((resp: any) => {
res.send(resp.data);
})
.catch(function(error: any) {
console.log(error.message);
});
}
It would be a good idea to cache the weather API response for a period of time and serve the cached response for subsequent requests.

Resources