uploading form data using axios to back end server such as node js
// Step 1: Import required modules
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
// Step 2: Create a FormData object
const formData = new FormData();
// Step 3: Append form fields to the FormData object
formData.append('username', 'john_doe');
formData.append('email', '[email protected]');
formData.append('profile_picture', fs.createReadStream('/path/to/profile.jpg'));
// Step 4: Make a POST request using Axios
axios.post('http://your-backend-api-endpoint.com/upload', formData, {
headers: {
...formData.getHeaders(), // Include necessary headers for form data
'Authorization': 'Bearer YOUR_ACCESS_TOKEN', // Include any required authorization headers
},
})
.then(response => {
// Step 5: Handle the response from the server
console.log('Server response:', response.data);
})
.catch(error => {
// Step 6: Handle errors
console.error('Error uploading form data:', error.message);
});
Make sure to replace 'http://your-backend-api-endpoint.com/upload' with the actual endpoint of your Node.js server and '/path/to/profile.jpg' with the correct path to the file you want to upload. Additionally, update the form fields and headers based on your specific requirements.