I am setting a cookie like below in a post function.
res.cookie('sessionID', req.sessionID, { path: '/' });
It sets it fine...but I cannot seem to delete it. I am deleting it in a put function, because I want to update some data and then clear the cookie.
app.put('/data/completed/:info', jsonParser, function(req, res){
if (!req.body) return res.sendStatus(400)
res.clearCookie('sessionID', { path: '/' });
console.log(req.cookies.sessionID);
});
Obviously I am doing something wrong I just can't figure out what.
You are clearing cookie of response. But checking for request. Try to check console.log(res.cookies.sessionID);
So the issue wasn't with the clearing of the cookie it was with me not ending the response process. As clarified on the Express documentation.
res.end([data] [, encoding])
Ends the response process. This method actually comes from Node core,
specifically the response.end() method of http.ServerResponse.
Use to quickly end the response without any data. If you need to
respond with data, instead use methods such as res.send() and
res.json().
So when I put the res.end() function in the code, everything works as expected and the cookie clears.
app.put('/reset/:completed',function(req,res){
res.clearCookie('sessionID', { path: '/' });
res.end();
});
Related
I have been facing a weird thing for several days and I had no luck of solving that so far. The problem is I have a React.js frontend , Node Express.js backend and MongoDB, when I'm making requests to /api/users/update-pwd with proper parameters using axios, it doesn't update the password, but it returns 200. Then, I tried some routes such as /api/users/psosp. To my surprise, It also returned 200. I couldn't find the reason for that. Any helpful tip is highly appreciated.
Axios.post("/users/update-password",{
password: n_pwd
}).then(
res => {
alert("Password Updated")
}
).catch(err => {
console.log(err)
alert("An error occured")
})
Make sure that you don't have code like this in your backend.
router.post('/users/:userId',(req,res)=>{
// some operations
res.send();
});
router.post('users/update-password',(req,res)=>{
// some operations
res.send();
});
What above does is that it doesn't matter whatever you use in place of * /users/*/
the first route will be called by default
and also make sure that you did not use
app.use('*',(req,res)=>{
// some operations
res.send();
})
For any API call irrespective of the path the above code will be called.
In this example, I have two routes - the first is a Get route and the second is a Post route. I want the information gathered in the get route to be included in the post route. I tried using .then and some basic boolean if logic but I cannot get these routes to run synchronously.
leadFormObj = {};
$.get("/getID/"+leadFormObj.parentEmail, function(event){
console.log("getting an ID");
console.log(event[0].id);
leadFormObj.parentID = event[0].id;
});
console.log(leadFormObj);
$.post("/addChild", leadFormObj, function(data) {
console.log(leadFormObj);
console.log("sent");
});
In the example above, I have a standard object (i've shown it blank in this example). The first get route will run and pass in a new key value pair to the object. I then want to pass this updated object to the post route but I'm not sure how to do this.
Would I use nested routes to do this?
Thanks!
Why don't you put the post request inside the callback of the get request
$.get("/getID/"+leadFormObj.parentEmail, function(data){
$.post("/addChild", {parentID: data[0].id}, function(data) {
console.log("sent");
});
});
I'm trying to implement an asynchronous method which makes a POST call to a certain API and retrieves its data, and then stores the result in the user's session. The task itself seems to be quite easy, but it gets problematic when I do it the 'fire-and-forget' style.
I do not wish to wait for the result to come back from the external API, but instead let the user load his requested page and continue browsing. Only when the response is ready, I want it saved in the session.
Everything seems to be working fine, but the only problem is the moment I set the session and proceed to the next route, everything gets lost as if I never set it in the first page. Debugging the code also shows that the process completes without any errors whatsoever, therefore I suspect an issue with setting the session after the response headers are already set. Can't seem to understand why that should be an issue, though.
I am using nodejs with express, and mongodb for session & database handling.
router.get('/myroute', function(req, res, next) {
request({
url: endpoint,
method: "POST",
json: true,
body: jsonData
}, function(error, response, body) {
req.session.mykey = 'some response';
});
res.redirect('/otherroute');
});
router.get('/checkresult', function(req, res, next) {
res.json(req.session.mykey);
});
I think you'll need to explicitly call save.
function(error, response, body) {
req.session.mykey = 'some response';
req.session.save();
}
https://expressjs.com/en/resources/middleware/session.html#sessionsavecallback
This method is automatically called at the end of the HTTP response if the session data has been altered
In your case this automatic save will be occurring too soon.
Platform: node.js + express and request modules (beginner).
HI, I got simply router.get followed by a request and I want to modify the headers it get from external server, and send it to the user that requested the specific data.
router.get('/', function(req, res){
var someUserRequest = request('http://google.com', function(error, resp, body){
if (error){
console.log(error);
}
console.log(resp.headers); //lets assume that there is 'x-content-type-options' that I don't want for example
}
req.pipe(someUserRequest).on('response', function(response){
delete response.headers['x-content-type-options'];
console.log(response.headers); // everything looks fine here - no 'x-content-type-options'
}).pipe(res);
});
module.exports = router;
So it seams that there is no 'x-content-type-options'. However when I check this out in chrome developer tools (network) I can clearly see 'x-content-type-options: nosniff' - even when I clear all history/cache.
So why it's not working? Can somebody explain me where is the error?
I think that you might need to splice the array instead, try putting a test condition before and after you
delete
to see if
['x-content-type-options']
exists in response.headers.
If it does then you can probably splice instead.
Read more on delete here
I'm a beginner in Express.js and I'm confused by these two keywords: res.end() and res.send().
Are they the same or different?
First of all, res.send() and res.end() are not the same.
I would like to make a little bit more emphasis on some key differences between res.end() & res.send() with respect to response headers and why they are important.
1. res.send() will check the structure of your output and set header
information accordingly.
app.get('/',(req,res)=>{
res.send('<b>hello</b>');
});
app.get('/',(req,res)=>{
res.send({msg:'hello'});
});
Where with res.end() you can only respond with text and it will not set "Content-Type"
app.get('/',(req,res)=>{
res.end('<b>hello</b>');
});
2. res.send() will set "ETag" attribute in the response header
app.get('/',(req,res)=>{
res.send('<b>hello</b>');
});
¿Why is this tag important?
The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed.
res.end() will NOT set this header attribute
First of all, res.send() and res.end() are different.
res.send() will send the HTTP response. Its syntax is,
res.send([body])
The body parameter can be a Buffer object, a String, an object, or an Array. For example:
res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });
See this for more info.
res.end() will end the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse. It is used to quickly end the response without any data. For example:
res.end();
res.status(404).end();
Read this for more info.
res.send() implements res.write, res.setHeaders and res.end:
It checks the data you send and sets the correct response headers.
Then it streams the data with res.write.
Finally, it uses res.end to set the end of the request.
There are some cases in which you will want to do this manually, for example, if you want to stream a file or a large data set. In these cases, you will want to set the headers yourself and use res.write to keep the stream flow.
In addition to the excellent answers, I would like to emphasize here, when to use res.end() and when to use res.send() this was why I originally landed here and I didn't found a solution.
The answer is very simple.
res.end() is used to quickly end the response without sending any data.
An example for this would be starting a process on a server:
app.get(/start-service, (req, res) => {
// Some logic here
exec('./application'); // dummy code
res.end();
});
If you would like to send data in your response then you should use res.send() instead:
app.get(/start-service, (req, res) => {
res.send('{"age":22}');
});
Here you can read more:
http://expressjs.com/en/4x/api.html#res.end
http://expressjs.com/en/4x/api.html#res.send
res.send() is used to send the response to the client where res.end() is used to end the response you are sending.
res.send() automatically call res.end() So you don't have to call or mention it after res.send()
res is an HttpResponse object which extends from OutgoingMessage. res.send calls res.end which is implemented by OutgoingMessage to send HTTP response and close connection. We see code here