For my job I have to create a login on a page. I send my login data to the server using the fetch API and when it was successful, I will receive back a cookie.
However, I do see a cookie sent to me in my response, but I don't know how I can access it or set it on my front-end? Anyone knows how to do this?
Fetch function
const submitForm = async values => {
try {
const body = {
user: {
email: values.email,
password: values.password,
},
};
// don't mind the strange syntax here, it's a slightly modified fetch function wrapper
const response = await fetch.post('users/sign_in', {
body,
});
} catch (error) {
console.log('error', error);
}
};
Response I get from server, how do I actually get access to this cookie in javascript, or how can I immediately add it as a cookie in my browser?
Cookies of browser is still empty
Related
I was working on admin registration and admin data retrieving react app. The registration works fine but retrieving admin data is crushing my backend. I have encountered this error when call the given endpoint from my react app. But when I call it from Postman it works very fine. And when I see the console on my browser my react app sends two calls simultaneously instead of one. On these calls my app crushes. If any one can show me how to solve this problem?
For backend = Node.js with express.js framework
For frontend = React
This is the error I am getting
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot remove headers after they are sent to the client
at new NodeError (node:internal/errors:372:5)
at ServerResponse.removeHeader (node:_http_outgoing:654:11)
at ServerResponse.send (C:\Users\Momentum\Documents\The Technologies\Madudi-App-Api\node_modules\express\lib\response.js:214:10)
at C:\Users\Momentum\Documents\The Technologies\Madudi-App-Api\api\index.js:22:72
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
[nodemon] app crashed - waiting for file changes before starting...
This is how I setup my endpoint and changed the data to a string in order to get simple response but it crushes
const makeHttpRequest = (controller, helper) => {
const makeRequest = (req, res) => {
try {
var data = "Trying response";
res.status(200).send({ status: true, data: data });
} catch (error) {
console.log(`ERROR: ${error.message}`);
res.status(400).send({ status: false, error: error.message });
}
};
return { makeRequest };
};
const makeApi = ({router, controller, helper}) => {
router.get("/test", (req, res) => res.send("Router is Woking..."));
router.get("/admin/get_all_admins", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));
}
module.exports = { makeApi }
And this is the call from my react app
export default function GetAllUsers() {
useEffect(() =>{
try{
const response = axios.get('http://localhost:5000/admin/get_all_admins').then(async (response) => {
console.log('response ', response)
return response.data;
});
}catch(error) {
return [];
}
}, [])
I'm not familiar with this method of responding to requests, but in my own opinion the error you are facing happens when you're sending multiple response.
This may be the asynchronous nature of JavaScript, there by causing another request to be sent after the function is done.
You should also try to return the response, so that once it's done it cancels out of the function. You can use the example below
const handler = (req,res) => {
return res.status(200).json(data)}
This particular error happens when you try to send more than one response for the same incoming request (something you are not allowed to do).
You are calling res.send() more than one for the same request on your server.
The first happens in the makeRequest() function.
The second time happens in this line of code:
router.get("/admin/get_all_admins", async (req, res) => res.send(await makeHttpRequest(controller, helper).makeRequest(req, res)));
You can't do that. You get ONE response per incoming request. So, either send the response in makeRquest() and don't send it in the caller. Or, don't send the response in makeRequest() and just return what the response should be and let the caller send it. Pick one model or the other.
I am not familiar with this way of setting up the server. Looks strange to me. However, in router.get("/admin/get_all_admins" your sending a response which calls a function makeHttpRequest that also sends a response. Thus you get an error Cannot remove headers after they are sent to the client because you're sending a response twice.
I've made a MongoDB GET request route named users/auth to create authentication by searching for the records provided in the request's body, inside the database. When I send the request via POSTMAN then it gives the expected response (eg: "true")
But when I tried to send the same request inside my react-app with AXIOS it gives an unexpected response(eg: false) with status code: ok. I'm not sure of what wrong I'm doing.
//some valid objects which should return true
//but it return's false
users = {
"email": 'abc#gm.com',
"password": 'abcdef'
}
axios.get('http://localhost:5000/users/auth', users)
.then(res => {
console.log(res.data);
//expected: true
// actual result: false
})
.catch(error => console.log(error))
I've read this problem but It didn't fixed my problem.
I've been trying to send a GET request to an api to fetch data using Axios but always get a response object with status, headers, config, agents etc and response.data is always empty.
For example, the following code returns me an Axios response object with the hasBody set to true and data being empty.
axios.get(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings/`).then(response => {console.log(response);
console.log(response.data);});
However, when I switched over to using Request library which has been deprecated, I am able to get the response body. For example, the following code works:
request(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings/`, { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body);
});
Can someone tell me what am I doing wrong and how can I get the response body using axios? I'm a beginner and have spent hours trying to figure out so I would really appreciate any form of help.
It's not an axios library issue. From what I can tell, the server does't like the user-agents starting with "axios/". Specifying some user agent gives you the expected result:
const axios = require("axios");
axios.get(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings`, {
headers: {
'user-agent': 'not axios',
}
}).then(response => {
console.log(response.data);
});
As for why the requests library works but axios does not: axios is setting the user-agent header to something like axios/0.21.1 or whatever version you have. requests on the other side, leaves the user-agent header unset. It's the server right to handle the request as he pleases.
I have verified the response from this URL https://fantasy.premierleague.com/api/leagues-classic/12000/standings/ - there is no data property in the response
Try like below to read the values:
It seem like your URL at https://fantasy.premierleague.com/api/leagues-classic/12000/standings/ had invalid response body.
I am using vue-recaptcha v3 on vue2 , and when I log response data of recaptcha request it is a fullfiled promise with a token and when I test it via postman and google verify api, it gets succeed.
but I don't know how to parse this promise and send the token to the Node backend using axios, my axios section doesn't work and I Get empty object {} at the backend side. anyone can help please?
methods: {
loginFunction: function() {
this.$recaptchaLoaded();
const token = this.$recaptcha('login');
console.log(token);
axios.post('http://192.168.27.167:3000/recaptcha',
{
token: token,
})
.then(response => {
}).catch(error => {
console.log(error)
})
it solved by a friend of mine as below with adding Async Await to the code and then at console log I get pure token to using for verification.
methods: {
loginFunction: async function() {
await this.$recaptchaLoaded();
// Execute reCAPTCHA with action "login".
const gresponse = await this.$recaptcha('login');
console.log(gresponse)
I am doing a registration method in Next.js. I need to hash the password when I put it into the database so for that I use bcrypt. It seems working but if I call the registration API it outputs a warning which says:
API resolved without sending a response for /api/register, this may result
in stalled requests.
Here is my code:
// imports and constants
export default async (req: any, res: any) => {
if (req.method === "POST") {
//some variables and validation schema
await db
.collection(COLLECTION)
.find({ email })
.count()
.then((result) => {
if (result > 0) {
return res.status(409).end();
} else {
bcrypt.hash(password, 10).then(function (hash) {
// <----- THE PROBLEM IS HERE
//password is the plainedPassword that I get from frontend
user.password = hash;
db.collection(COLLECTION).insertOne(user);
return res.status(204).end();//<<--- the request doesn't end here but goes forward..
});
}
// if I put another return.status(204).end(); here it works
});
} else {
return res.status(405).end();
}
};
It seems to be working, it stores the hash password into the DB, then I can make the login as well. However, I believe that warning could cause serious problems in the future.
I also logged a string before and after the bcrypt statement and I found out the problem is there.
I have found this answer but it did not help me.
In my case I was sending a POST request and expecting a response with a 200 that I wasn't receiving (with the same error that you have), so after that, my app couldn't continue with the normal workflow, the solution to that was sending a "dummy" response in json format, it could be something like:
return res.status(204).json({ message: "No content" });
It seems like nextjs always expect you to send some type of content.
Try returning something from the API function, modify your code like this:
return await db.collection()