I am creating structure for FormData in fetch API, but there is something that i am missing. it will be helpful if someone can help me. Here is the code.
const fetchFormData = async (url, method = 'POST', formData) => {
const secret = process.env.NEXT_PUBLIC_SECRET_KEY || '';
const token = Cookies.get('accessToken');
if (!secret) {
throw new Error('Secret key is not defined');
}
if (!token) {
throw new Error('Token is not defined');
}
const payloaddata = formData;
const nonce = generateNonce();
const timestamp = generateTimestamp();
const signature = generateSignature(JSON.stringify(payloaddata), secret, nonce, timestamp);
const headers = {
'Nonce': nonce,
'Timestamp': timestamp,
'Signature': signature,
'Authorization': `Bearer ${token}`,
};
try {
const response = await fetch(url, {
method,
headers,
body: formData,
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error uploading file:', error);
throw error;
}
};
export default fetchFormData;
And here i am consuming:
const formData = new FormData()
formData.append('file', bulkFile)
const apiUrl = `${process.env.NEXT_PUBLIC_API_URL_LIVE}/uploadProducts`
try {
const response = await fetchFormData(apiUrl,'POST',formData)
const responseData = await response.json()
if (!response.ok) {
throw new Error(responseData.message || `Failed to fetch data, status: ${response.status}`)
}
catch(error){
console.log(error.message)
}
i am trying to upload csv file on server but for error. Before that, i was using regular method and it was working absolutely fine but in fetch api structure, i got an error