django - 带有 django 后端的 webpacked vuejs/reactjs/angularjs 网站的 localhost 开发中的 csrf 和 cors 错误
问题描述
如何在 localhost 上运行我的 vuejs 应用程序并将其 API 调用发送到我部署的 django rest 框架后端而不会出现 cors 和 csrf 问题?
到目前为止,我有这些问题:
- 我无法从浏览器读取 cookie,因为它的域未设置为 localhost。我需要它来设置
X-CSRFTOKEN
django 的标题。 - 我收到 CORS 错误,因为 localhost 与我的域(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'
推荐阅读
- html - 一个普通 div 中的 2 个 div
- cmake - 在代理后面的 CMake 中获取依赖项
- react-native - 使用 ScrollView 和 FlatList 以表格格式显示数据,但我想修复第一列和第一行剩余的行和列应该滚动
- linux - 为什么有时 PACKET_TX_RING 性能下降,只能到达线速的一半
- c# - 在 ASP Webforms 应用程序上捕获 RFID 阅读器 Cardswipe
- r - 尝试向 ggplot 和 ggsmooth 添加多个图例
- facebook - 是否可以为一个应用程序设置多个显示名称?
- reactjs - 为什么不能对未安装的组件执行 React 状态更新?
- sql - Oracle sql - 基于其他列的查询
- javascript - 点击时手风琴没有展开。可能是什么问题?