Home > OS >  axios post data successfully but failed to assign location after response success instead res.json r
axios post data successfully but failed to assign location after response success instead res.json r

Time:07-31

axios script.js file

const creatClient = async (client) => {
  try {
    const res = await axios({
      method: 'POST',
      withCredentials: true,
      url: '/[url]',
      data: client,
    }).then(location.assign('/[newUrl]'));
  } catch (error) {
    console.log(error);
  }
};
submitbtn.addEventListener('click', (e) => {
  e.preventDefault;
  const name = document.getElementById('name').value;
  const phone = document.getElementById('phone').value;
  const createdATT = new Date(document.getElementById('date').value);
  const followUp = new Date(document.getElementById('date2').value);
  const images = document.getElementById('img').value;
  const insurance = document.getElementById('insurance').value;
  const client = { name, phone, insurance, images, createdATT, followUp };
  console.log(client);
  client ? creatClient(...client) : console.log('no object created');
});

controller file the console log for req.body [Object: null prototype] {*** the object ***}

const multer = require('multer');
const Client = require('../models/clientModel');

const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'public/img');
  },
  filename: (req, file, cb) => {
    const ext = file.mimetype.split('/')[1];
    cb(null, `user-${Date.now()}.${ext}`);
  },
});
const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cd(console.log('select image'), false);
  }
};
const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter,
});
exports.uploadImages = upload.single('images');
//
exports.createClients = async (req, res, next) => {
  try {
    if (req.file) req.body.images = req.file.filename;
    const newClient = { ...req.body };
    await Client.create(req.body).then(
      res.status(200).json({
        status: 'success',
        newClient,
      })
    );
  } catch (err) {
    console.log(err);
  }
};

also with postman sending request give success response with no errors i've tried location.replace() but also it didn't work for me and is there another trick from server to get to the desired location out from client side

CodePudding user response:

then accepts a callback as a parameter.

then(() => location.assign('/[newUrl]'))
  • Related