[Vuejs]-Csrf and cors errors in localhost development of webpacked vuejs/reactjs/angularjs website with django backend

0๐Ÿ‘

โœ…

I struggled with this for three days until I found this great solution.

I put the following in my vue.config.js and I initialized my http client with baseURL = โ€˜/apiโ€™

const fs = require('fs');
module.exports = {
  devServer: {
    proxy: {
      '^/api': {
        target: 'https://example.com',
        ws: true,
        changeOrigin: true,
        bypass: (req, res) => {
          if (req.headers && req.headers.referer) {
            url = new URL(req.headers.referer);
            url.host = 'example.com';
            url.port = '';
            req.headers.referer = url.href;
          }
        },
        cookieDomainRewrite: '',
      },
    },
    http2: true,
    https: {
      key: fs.readFileSync('./cert/key.pem'),
      cert: fs.readFileSync('./cert/cert.pem'),
    },
  },
};

There is another option which is setting something like local.example.com in your hosts file and creating whitelists etc in your settings.py but this solution is way cleaner and better.

You can use the following command to generate your self signed certificates. For some reason I was getting authentication errors when not using https.

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes -subj '/CN=localhost'

Leave a comment