我制作了一个Angular应用程序,可以使用在线api获取json并执行操作。 但是,尽管json相同,但是如果我尝试通过设置用django编写的服务器的本地url来仅更改json的url,则angular似乎将不再连接...
我的问题是,为什么如果使用在线云服务器,而不能使用本地云服务器呢?
我试图使该服务器“在云上”打开路由器的端口,还设置了ddns,并使用邮递员或浏览器似乎正常,但是当我尝试与angular连接时,仍然无法获取数据...
我确信100%的服务器将使用正确的json数据进行回答,因为django在控制台上打印出他收到了HTTP GET请求: http://i.imgur.com/TIQnIcR.png
我提醒您,HTTP角度请求可与其他api一起使用,但我仍会显示一些代码:
export class ProdottoService {
private prodotti: Array<ProdottoModel>;
constructor(private httpClient: HttpClient) {
this.prodotti = new Array<ProdottoModel>();
var url:string = "https://gist.githubusercontent.com/saniyusuf/406b843afdfb9c6a86e25753fe2761f4/raw/523c324c7fcc36efab8224f9ebb7556c09b69a14/Film.JSON";
var local_url:string = "http://127.0.0.1:8000/films/?format=json";
httpClient.get(local_url)
.subscribe((films : Array<Object> ) => {
films.forEach((film => {
this.prodotti.push(new ProdottoModel(film));
}));
}
);
}
getProdotti(): Array<ProdottoModel> {
return this.prodotti;
}
}
使用外部api的结果:
http://i.imgur.com/MT7xD9c.png
感谢advace的帮助:3
-编辑-是一个大问题
在Django settings.py文件中:
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'127.0.0.1:4200'
)
INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
但是我不知道是否有办法在Angular中设置CORS设置
答案 0 :(得分:0)
根据反馈,这是一个CORS问题。您的Django服务器正在获取请求并做出响应,因为localhost是Django开发环境中的隐式信任域,但未正确配置它来设置跨源标头,因此浏览器不允许您的应用查看响应,因为服务器没有明确授权该域。
这里的问题是您已经将CORS白名单设置为:
CORS_ORIGIN_WHITELIST = ( 'localhost:8000', '127.0.0.1:4200' )
它必须像这样:
CORS_ORIGIN_WHITELIST = ( 'localhost:4200' )
angular在localhost而不是127.0.0.1上运行,即使这是localhost的别名,您的浏览器仍会将它们区分为CORS。另外,您无需将要提供服务的域列入白名单,因为该域来自同一域,所以不会跨越任何域。
答案 1 :(得分:0)
在屏幕快照中,响应似乎是键入“ document ...”的东西。最简单的解决方法是仅将代码转换为JSON。
var menu = document.getElementById("menu");
function contextMenu(e) {
var atr = e.target.inspect; // or this.inspect and remove e parameter
// go on here, 'atr' will be 'undefined' if the element has no attribute 'inspect'
}
Array.prototype.forEach.call(
document.getElementsByClassName("item"),
function (element) {
element.addEventListener('contextmenu', contextMenu, false);
}
);
这是错误的答案,因为由于其他答案中的CORS问题而被设置为该答案。