[Vuejs]-Vue Js Form post issues to server

0👍

You can try this code below:

Backend: You can change your backend with this code below

router.post('/insert', function(req, res, next) {
  console.log(req.body);
  mongo.connect(url, function(err, db) {
    db.collection('users').insertOne(req.body, function(err, result) {
      if(err) return res.status(500).send(err);
      return res.status(200).send(result.ops[0]);
      db.close();
    });
  });
});

The code above only an example for simple case. If you want to add assert, then you can make sure it’s working fine. If the simple code above it’s working, then you can add assert.

Make sure you’ve been install cors on your server and add it in your app.js or server.js this code below:

app.use(cord({origin: "*"});

And then, make sure you call your endpoint use: http://. Not only localhost but http://localhost.

FrontEnd

onSubmit(evt) {
  evt.preventDefault()
  axios({
          method: 'post',
          url: '/insert', // make sure your endpoint is correct
          data: this.form
      })
      .then(response => {
          //handle success
          console.log(response.data);
          // do some stuff here: redirect or something you want
      })
      .catch(error => {
          //handle error
          console.log(error.data);
      });
},

Make sure your endpoint is correct.

I hope it can help you.

Leave a comment