首页 > 解决方案 > 带有 django 后端的 webpacked vuejs/reactjs/angularjs 网站的 localhost 开发中的 csrf 和 cors 错误

问题描述

如何在 localhost 上运行我的 vuejs 应用程序并将其 API 调用发送到我部署的 django rest 框架后端而不会出现 cors 和 csrf 问题?

到目前为止,我有这些问题:

标签: djangoreactjsvue.jswebpackdjango-rest-framework

解决方案


我为此苦苦挣扎了三天,直到找到了这个很好的解决方案。

我将以下内容放入我的vue.config.js并使用 baseURL = '/api' 初始化了我的 http 客户端

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'),
    },
  },
};

还有另一个选项是local.example.com在您的主机文件中设置类似的内容并在您的文件中创建白名单等,settings.py但此解决方案更干净、更好。

您可以使用以下命令生成自签名证书。出于某种原因,我在不使用 https 时遇到了身份验证错误。

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

推荐阅读