I am making a system of getting file from client by multipart/form-data request. so i need two headers. one for files(type of multipart/form-data), and one for JWT(for check authorization of user)(type of string). but when i trying to send these two headers, i get an error message of "Error: Failed sending data to the peer"
So i tried to send the JWT that inside of multipart/form-data.(like the image below).
But i can't found 'x-jwt'(key of JWT) property in my request.
How can i get many headers form request with multipart/form-data.
Below code is UploadMiddleware that i am trying to get JWT from request.
And I am useing NestJs and multer to get image from client, and Insomnia to test my system.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { JWT_KEY } from 'src/auth/jwt/jwt.constant';
import { JwtService } from 'src/auth/jwt/jwt.service';
import { UserService } from 'src/user/user.service';
@Injectable()
export class UploadMiddleware implements NestMiddleware {
constructor(
private readonly jwtService: JwtService,
private readonly userService: UserService,
) {}
async use(req: Request, res: Response, next: NextFunction) {
try {
//JWT_key is 'x-jwt'
if (JWT_KEY in req.headers) {
const token = req.headers[JWT_KEY];
const decodedToken = this.jwtService.verify(token.toString());
if (
typeof decodedToken === 'object' &&
decodedToken.hasOwnProperty('id')
) {
const getUser = await this.userService.findUser({
id: decodedToken.id,
});
if (getUser.sucess) {
req['user'] = getUser.user;
}
}
}
} catch (e) {
console.error(e);
}
next();
}
}
You are trying to do two things in one middleware. And that's not a good idea. Because when you need to check if the user is authenticated elsewhere, you need to copy and paste your code in this place. This is a bad pattern. Instead of that you should create separate middleware or guard(check nestjs doc about guards). And this guard will check if user is authenticated or not. If it is then guard let request further. In other case guard throw Http exception 401 Unauthorized. As for file uploading you could use multer. About file uploading check corresponding section of nestjs doc(how to upload file nestjs doc).