【问题标题】:Handling CORS when using django, angular and gulp使用 django、angular 和 gulp 时处理 CORS
【发布时间】:2017-01-23 13:54:53
【问题描述】:

我有一个项目,我正在 Django 之上构建并使用 AngularJS 1 来处理前端。此外,我正在尝试使用 Gulp,以便我可以享受一些浏览器同步功能。下面是我用来触发 Gulp 服务器但同时使用 Django 服务器作为代理的一段代码。

gulp.task('browser-sync', function() {
browserSync.init({
    proxy: "localhost:8000"
});
});

但是,我遇到了 CORS 的问题。我收到的错误消息如下:

XMLHttpRequest 无法加载 http://localhost:8000/static/js/data.json。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:3000' 因此不允许访问。

有问题的 data.json 文件是我用作前端开发数据源的文件,因为我还没有创建后端。

这是我如何使用 Angular 的 $HTTP 从 JSON 文件中获取数据的示例:

marksApp.factory('getSubjectsService', ['$http',function($http){
return {
    getSubjectNames : function(stdNum){
        return $http.get('http://localhost:8000/static/js/data.json')
        .then(function(data){
            return data.data;
        });
    }
};
}]);

【问题讨论】:

  • enable-cors.org/server.html - 如何在众多服务器环境中启用 CORS
  • @JaromandaX 看着我的问题,我是否需要在 django、angular 或 gulp 中解决 CORS 问题
  • 您需要在要允许跨源资源共享的服务器上启用 CORS - http://localhost:8000
  • 让我看看如何使用 django 服务器做到这一点。

标签: javascript angularjs json django gulp


【解决方案1】:

您需要将 CORS 标头添加到您的 Django 响应中。

有一个名为django-cors-headers 的流行 Django 应用程序可以简化这一过程。检查https://github.com/ottoyiu/django-cors-headers

【讨论】:

  • 我试过了,但它不起作用。我的服务器上有一个独立的 js 文件,从该文件中的错误来看,我需要启用 cors。有什么办法可以将 CORS 标头添加到 json 文件中?
  • CORS 标头应该添加到服务器端。你试过CORS_ORIGIN_ALLOW_ALL = True。或适当设置CORS_ORIGIN_WHITELIST = ()
【解决方案2】:

我正在使用 http-proxy-middleware 进行代理。

我这里有一个 django rest 框架:

url(r'^api/', include(router.urls)),

这里还有 gulp 代理:

var proxyMiddleware = require('http-proxy-middleware');
..snip..
server.middleware = proxyMiddleware('/api', {target: 'http://localhost:8000', changeOrigin: true});

在我的例子中,结果是 localhost:3000/api 代理到 localhost:8000/api,所以你不需要 CORS 标头。

这样的东西应该适合你:

$http.get('/static/js/data.json')

server.middleware = proxyMiddleware('/static', {target: 'http://localhost:8000', changeOrigin: true});

祝你好运。

见:https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2020-05-01
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多