create async thunk:
this is my node js api route
router.post('/', upload.single('image'), protect, setAd)
this is my react js code
export const sellBike = (bikeData) => API.post("/", bikeData);
my react js api
const API = axios.create({baseURL:"http://localhost:8000"});
CodePudding user response:
Generally for uploading a photo on the nodejs they use multer package. You can see all details on its document. Also, you should set multipart/form-data on request's header. Here is the link
I guess you can upload a photo on backend after you read those links
CodePudding user response:
example from my project:
- convert img to string
img.toDataURL()
- Post to backend
const saveAvatar = () => axios.post<string[]>(
http://${DOMAIN}/profile/saveAvatar/${id}
, { avatar } );
Take and save
profile.post('/saveAvatar/:id', async (req, res) => { try { const { id } = req.params; const { avatar } = req.body; const data = avatar.replace(/^data:image/\w ;base64,/, ""); const buf = Buffer.from(data, 'base64');
const login = await pool.query( "SELECT login FROM accounts WHERE id = $1", [id] ); fs.writeFile(`${userImgPath}/app_data/images/users/${login.rows[0].login}.png`,
buf, (err) => { if (err) throw err; console.log('The file has been saved!'); }); } catch (err: any) { console.error(err.message); } });