Express Sessions GET vs POST requests - node.js

I can access the session object data when using post method but session object data is null when using get method.How can i access session object data using get method.
I am using express-session.
Front-end Code
For POST method
axios.post(url,{params:data},{withCredentials: "true"})
For GET method
axios.get(url,{params:data},{withCredentials: "true"})
Back-end Code
Middleware for both get and post requests.
router.use((req: Request, res: Response, next: NextFunction) => {
console.log(req);
if (req.session && req.session.username) next();
else res.status(401).send("Unauthorized");
});

axios.get() only takes two arguments (not three). The first is the URL and the second is the options. You are passing the options in the third spot which axios.get() does not look at. Therefore, it never sees the withCredentials: true option and thus doesn't send the session cookie and thus your server doesn't know how to find the session.
So, change from this:
axios.get(url,{params:data},{withCredentials: "true"})
to this:
axios.get(url,{withCredentials: "true"})
Note, there is no data argument for axios.get() because a GET does not send a request body, only a POST or PUT send the body. See the doc here.
Note: This bites people regularly with axios. .post() and .get() need a different number of arguments.

Related

use req.body data from the api route handler in a external javascript file in nextjs api

I need to send the req.body (data received from the client to API route via post request) data from the API route to a separate javascript file in the backend api.
const payload = {}
const handler = async (req, res) => {
payload = req.body
res.status(200).json({ status: 'success' })
}
export default handler
I declared a variable outside the route handler function and assigned req.body to it, but then I realized that I can't use this global variable inside the handler function. I don't know the reason. Is there any specific way of achieving what I'm trying to achieve here?
I request to please elaborate the use case a bit more. Based on current requirements.
I can understand that-
You need to send the req.body to another JavaScript file. Now here can be 2 cases.
You need to store req.body in a file, and use it for later processing.
Pass the req.body to another function which is present in another JavaScript file.
In this case, you can export the function from another file and import in this main file and call the function in your controller and pass req.body as Payload.
I think your use case will be second one, if not please update question and I will be happy to help you out.

NodeJs with Express not parsing form data from node-fetch

I'm creating two APIs with NodeJS, Express, and TypeScript. One API will take a request with a content type of multipart/form-data, and will use the body in the request to make another request to a second API.
I'm using Postman, so the chain of request looks something like this
Postman -> First API -> Second API
I use node-fetch to make a request from the first API to the second one. The body of the request is a FormData, which contains some files and key-value pairs.
const form = new FormData();
// File for profile picture
const profilePictureBuffer = await (await fetch(user.profilePicture)).buffer();
form.append('profilePicture', profilePictureBuffer);
// File for ID Card
const idCardBuffer = await (await fetch(user.idCardUrl)).buffer();
form.append('idCard', idCardBuffer);
// This part iterats over the obsect of 'user',
// which contains other key-value pairs
Object.entries(user).forEach((data) => {
form.append(data[0], data[1]);
});
// Make POST request to second API
const pinterUser = await fetch(secondAPIURL, {
method: 'post',
body: form,
headers: form.getHeaders()
});
I ran both of the APIs on localhost so that I can monitor the logs for any bugs. As I make a request from Postman to the first API, then the first API make another request to the second API, I got the following error log in the terminal for the second API
TypeError: Cannot read property '0' of undefined
After some investigation, I found out that, in the second API, the req.body and req.files are empty objects. This means that Express did not parse the incoming request. Note that I've also already a multer middleware to handle the files in the request.
Furthermore, I have added the following lines of code in my server.ts file for the second API
/** Parse the body of the request */
router.use(express.urlencoded({ extended: true }));
router.use(express.json());
However, when I tried making the request from Postman, it returns a successful response.
I'm not really sure what's going on here. I've tried looking for some answer regarding this similar issue, but most of them suggest adding urlencoded and json, or using some other library to handle parsing form data.
In my case, the first suggestion doesn't solve my problem since I already added them from the start, and the latter is what I'm trying to avoid.
I wonder if anybody could point out what I was missing here? Thanks in advance

Node.js: is request unique?

In node.js, when using https-module and createserver. When user makes request to httpsserver, is request unique or can different request has same request (id?). If it is unique, which property should be to use?
The request argument in an http request handler is a Javascript object and every one is unique. They are never reused. That object is documented here.
There is no such thing as a request ID in the node.js http library. If you want to make your own request ID, you can do that yourself by just assigning a symbol as a property of the request object. You can pick any property name to use that does not conflict with existing properties.
Since this is a bit of an unusual request, I'd ask you why you're trying to do this because there may be a better way to solve your problem than trying to make a request ID. If you show your actual code and what you're trying to do, we could probably help you more specifically.
If you were using Express, you could set your own request ID with some middleware like this:
// set request ID
let reqCntr = 0;
app.use((req, res, next) => {
req._localID = reqCntr++;
next();
});
Just place this middleware before any other request handlers that wish to use the id. You can pick any non-conflicting property name. I picked _localID.

Express Request Post-Processing

I haven't been able to find anything in express's documentation, but is there such thing as request post processing? I am using a custom token authentication scheme using passport and I would like the ability to automatically update the token in a response header after making a request, mostly a hashed timestamp for authentication purposes. For discussion purposes, let's say I want the following function to execute after each request:
function requestPostProcess(req, res){
if (res.status == 200)
{
res.token = updateToken();
}
}
Ideally, I'd like to be able to do this without having to call next() in each of my routes. Is that even possible?
If you want to add the token to the response,
1) You can create a middleware that adds the token as soon as the request comes, and before it is processed. Put this before request handlers.
Example,
app.use(function(req, res, next){
res.token = updateToken();
next();
})
The glitch here is that, the token will come with all the responses but that can be something you may accept, since it is a timestamp. Plus you can even handle errors using middlewares, and remove the token when the status is not 200.
Advantage: minimal changes required, with proper error handling it works great.
Disadvantage: it tells the time when request was received and not when the response was ready.
2) If you want to put the response after the process is completed, meaning the time when the response was ready, then you may need to create a utility function that sends back all the responses, and you always call that function. That utility function will check the status and appends the token.
function sendResponseGateway(req, res){
if (res.status == 200)
{
res.token = updateToken();
}
res.send()
}
Now whenever you are ready to send response, you can call this function.
Disadvantage: function needs to be called everywhere and you will not be writing "res.send" anywhere.
Advantage :you have a gateway of sending response, you can do additional stuff like encoding, adding more headers etc. in that function and all those response modification stuff happens at one place.

$resource.query() parameters fail to arrive at server

Trying to implement a RESTful API using Node.js and Angular.
On the client side, I define a resource called songResource with the $resource function in Angular.
I then call the API with this method:
$scope.displayArray = songResource.query(
parameters, // an object containing various settings
function(value, responseHeaders) { // success callback
console.log('Success!',parameters);
...
},
function(httpResponse) { // error callback
console.log('Error!');
...
}
);
On the server side, the route resolves, but the parameters do not come over. (In other words, req.params is an
empty object.) The rest of the service retrieves and sends zero records. My client receives the zero records and
hits the success callback, where I can tell that the API call succeeded.
Why aren't the parameters coming over to the API, and how do I fix this?
Found out what I was doing wrong. My parameters come in through the query string. Therefore, I need to use req.query rather than req.params to get the parameters.

Resources