CSRF 和 CORS 错误在 Webpack vuejs/reactjs/angularjs 网站与 django 后



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

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

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

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

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

最新更新