can't receive file with multer (node.js-nuxt3) - node.js

I use nuxt3/node.js with multer ,
i can't store or receive file in my server and i can't see req.file in root, its empty all time.
server Code:
const upload = multer({ dest: './uploads/' })
router.post('/sendNewQuestionCSV', upload.single('csv'),adminControler.sendNewQuestionCSV.bind(adminControler))
and my FrontEnd Code with nuxt3:
async function fileSelected(e) {
let formData = new FormData();
formData.append("csv", e.target.files[0]);
const res = await $postFetch("/admin/sendNewQuestionCSV", formData, {
"Content-Type": "multipart/form-data",
});
}
note:$postFetch is an method i made my self use fetch and third argument is "headers". its a nuxt3 Plugin
this Plugin code:
export default defineNuxtPlugin(async () => {
return {
provide: {
postFetch: async (url, body,headers={}) => {
let token = useCookie('token');
return await $fetch(url, {
method: 'post',
body: { token: token.value, ...body },
baseURL: useRuntimeConfig().API_BASE,
...headers
}).catch((error) => error.data)
}
}
}
})

try using .append to add the token:
postFetch: async (url, body,headers={}) => {
let token = useCookie('token');
body.append('token', token.value);
return await $fetch(url, {
method: 'post',
body: body,
baseURL: useRuntimeConfig().API_BASE
}).catch((error) => error.data)
}
EDIT
also try removing headers

Related

Send blob pdf file from #react-pdf/renderer via rest API to Nest-js server that use fileInterceptor

Im unable to send blob pdf file that comes from #react-pdf/render.
first I'm tring to convert that blob into a file using new File()
<BlobProvider
document={<Document />}
>
{({ blob, url, loading, error }) => {
buildPdfFile(blob);
return <div />;
}}
</BlobProvider>
const fileRef = useRef<File | null>(null);
const buildPdfFile = (blob: any) => {
const file = new File(
[blob],
`${get(resumeData, "ownerName", "")}_${get(
resumeData,
"ownerId",
""
)}_ficha_de_inscripción.pdf`,
{
type: "application/pdf",
}
);
fileRef.current = file;
console.log(fileRef.current);
};
const handleOnSubmit = () => {
dispatch(sendPdfToServer(fileRef.current!));
};
once I got that file I'm tried to send it using formdata in a POST request with application/pdf as content-type to my nestjs app
const sendPdfToServer = (inscriptionPdf) => {
const jwt = getJWT();
const options = {
headers: new Headers({
"content-type": "application/pdf",
Authorization: `Bearer ${jwt}`,
}),
};
const formData = new FormData();
formData.append("file", inscriptionPdf, inscriptionPdf.name);
const path = `${url}`;
try {
const response = await fetch(path, {
...options,
method: "POST",
body: formData,
});
}
catch (e) {
console.log(e);
}
}
but in the endpoint I'm using, the file is never intercepted, it shows as undefined
#Post('sendMail')
#UseInterceptors(
FileInterceptor('file', {
storage: diskStorage({
destination: './uploads/emailsTemporalFiles',
filename: (req, file, cb) => {
console.log('file ->', file);
const fileName: string = path
.parse(file.originalname)
.name.replace(/\s/g, '');
const extension: string = path.parse(file.originalname).ext;
cb(null, `${fileName}${extension}`);
},
}),
}),
)
async sendMail(#Res() response, #UploadedFile() file) {
this.logger.log(` | sendMail`);
console.log(file); // it prints undefined
}

How to change fetch API link for deployment?

This is a method to fetch data from an API. I have used the MERN stack. I hosted this application on Heroku. The problem is that I can't understand how to change the link to fetch the API because on Heroku the app is running at a different port every time.
const SendData = async (e) => {
e.preventDefault();
await fetch('http://localhost:4000/Login',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
Email,
Password
})
})
.then(HandleErrs)
.then((res) => {
return res
}).then((res)=>{
const {UserName}=res;
// console.log(UserName);
setCredentials({
UserName,
Email,
Password
})
})
.catch((err) => {
getErr(ERR);
console.log(err)
})
}
Probably this will not give a direct answer to your question, but its a good practice,
What we normally do is create a separate file for api details
for ex:
api.js
//REACT_APP_SERVER_URL is a env variable in .env file
const rootUri = process.env.REACT_APP_SERVER_URL
? process.env.REACT_APP_SERVER_URL
: 'http://localhost:3001';
const apiVersion = 'v1';
const apiBasePath = `${rootUri}/api/${apiVersion}`; //this is the base path
export const userApis = {
all: {
url: `${apiBasePath}/users`,
method: 'GET',
},
update: {
url: `${apiBasePath}/user`,
method: 'POST',
},
};
this is how we use it
const fetchAllUser = () => {
const api = userApis.all;
fetch(api.url, {
method: api.url.method,
body: JSON.stringify(request)
}...

parsing profile photo from ms graph on nodejs

I'm trying to parse the logged in user's photo on node.js using graph API and something is not correct about the generated base64, I've tried different combinations and the photo is always corrupt.
export async function getPhotofromMsGraph(
accessToken: string,
): Promise<string | undefined> {
const config = {
headers: {
Authorization: `Bearer ${accessToken}`,
ResponseType: 'arraybuffer',
},
};
return axios
.get(graphConfig.graphPhotoEndpoint, config)
.then((response) => {
const { data } = response;
if (data) {
var imageType = 'image/jpeg';
var imageBytes = Buffer.from(data).toString('base64');
var imageSrc = `data:${imageType};base64,${imageBytes}`;
return imageSrc;
}
return undefined;
})
.catch((error) => {
throw error;
});
}

How to download a file from a server, and and post it again in another one (Node.js)

In my node application, I want to get a file from one server, and then upload it into another server. I have the following code:
const axios = require("axios");
const FormData = require("form-data");
const { createWriteStream, createReadStream } = require("fs");
const response = await axios({
url: "https://first-server/image.png",
method: "GET",
responseType: "stream",
});
await new Promise((res) => {
response.data.pipe(
createWriteStream("someFile.png").on("finish", () => {
res();
})
);
});
const form = new FormData();
form.append("file", createReadStream("./someFile.png"));
const postHeaders = {
headers: {
Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("https://second-server.com/api", form, postHeaders)
.then((response) => {
console.log(JSON.stringify(response.data));
})
This code works, but I think it's not the right way to do this, since it writes the retrieved file into the local disc before posting it again into the second server. I need to be able to upload the file without writing it into the local disc. Is there any way?
Just replace form.append("file", createReadStream("./someFile.png")); with
form.append("file", response.data);
Both response.data and createReadStream("./someFile.png") are readable stream.
Note: You can directly transfer returned stream data without any need to create temporary file.
const axios = require("axios");
const FormData = require("form-data");
axios({
url: "http://localhost:3000/temp.png",
method: "GET",
responseType: "stream",
}).then(response => {
response.data.on("data", function(data) {
const form = new FormData();
form.append("file", data);
const postHeaders = {
headers: {
// Authorization: "Bearer " + env("APY_KEY"),
...form.getHeaders(),
},
data: form,
};
axios.post("http://localhost:8000/api", form, postHeaders)
.then((response) => {
// console.log(JSON.stringify(response.data));
})
.catch(function(error){
console.log(error)
});
});
})
.catch(function(error){
console.log(error)
});

NodeJS Axios request returning an odd string

I'm sending a GET request to a third party API and it is returning a odd string (supposed to be an image).
axios.get(`${URL}/test`, {
headers: {
'Content-Type': 'application/json',
},
auth: {
username: USERNAME,
password: PASSWORD
},
responseType: 'blob'
})
.then(async (response) => {
console.log(response.data)
return res.json(response.data);
})
.catch((err) => {
console.log(err);
return res.json("ERROR");
});
The response is:
"����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000C
How can I convert it to an image or image/url?
Thanks
You can try this
const Fs = require('fs')
const Path = require('path')
const Axios = require('axios')
async function downloadImage () {
const url = 'https://unsplash.com/photos/AaEQmoufHLk/download?force=true'
const path = Path.resolve(__dirname, 'images', 'code.jpg')
const writer = Fs.createWriteStream(path)
const response = await Axios({
url,
method: 'GET',
responseType: 'stream'
})
response.data.pipe(writer)
return new Promise((resolve, reject) => {
writer.on('finish', () => { /* Add your code here */ resolve(); })
writer.on('error', () => { /* Add your code here */ reject(); })
})
}
downloadImage()

Resources