0
methods: {
onclicksubmit: function () {

const user = {
    firstname: this.firstname
  }
  const options = {
    method: 'POST',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify(user)
  };
  fetch('http://localhost:3000/register', options).then(response => {
    console.log('success', response);
  }).catch((error) => {
    console.error('Error:', error);
  });
},

When I click on the submit button it should send the data to the database but there is an error appearing which says 'failed to fetch.' This is the backend code:

    app.use(bodyParser.json())
app.post('/register', function (req, res) {

  res.send({
firstname: req.body.firstname,


  })
  console.info("Request body: " + JSON.stringify(req.body));

  db.collection('user').insertOne(req.body, req.body.firstname, function (err, res) {
      if (err) return console.log(err)
      else res.send('success!')

      console.log('saved to mongodb');


    })
});
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • hard to say without looking at what `http://localhost:3000/register` is doing? Are you able to access this urk successfully using postman? – Ashish Modi Jan 16 '20 at 21:28
  • yes postman is working – Sreenath Minthu Jan 16 '20 at 21:29
  • does it give something more about error? like inner error etc. – Ashish Modi Jan 16 '20 at 21:33
  • Thank you for the reply. It says "Access to fetch at 'http://localhost:3000/register' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." – Sreenath Minthu Jan 16 '20 at 21:34
  • when you try to access a url from browser which is not in the same domain you get this error. Follow this link - it should fix issue for you - https://stackoverflow.com/a/18311469/1021796 – Ashish Modi Jan 16 '20 at 21:39

1 Answers1

0

You are trying to make a request to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. When you are using postman they are not restricted by this policy.

You could use code like this to enable CORS.

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    next();
});

OR

const express = require('express')
const cors = require('cors')
const app = express()

app.post('/register', cors(), (req, res, next) => {
})

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35