【问题标题】:csrf and cors errors in localhost development of webpacked vuejs/reactjs/angularjs website with django backend带有 django 后端的 webpacked vuejs/reactjs/angularjs 网站的 localhost 开发中的 csrf 和 cors 错误
【发布时间】:2020-01-16 11:58:36
【问题描述】:

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

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

  • 我无法从浏览器读取 cookie,因为它的域未设置为 localhost。我需要它来为 django 设置 X-CSRFTOKEN 标头。
  • 我收到 CORS 错误,因为 localhost 与我的域 (example.com) 的来源不同
  • 我收到引用不匹配的错误。

【问题讨论】:

    标签: django reactjs vue.js webpack django-rest-framework


    【解决方案1】:

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

    我将以下内容放入我的 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'
    

    【讨论】:

      猜你喜欢
      • 2016-04-20
      • 2020-05-27
      • 2015-02-08
      • 2016-04-19
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      相关资源
      最近更新 更多