【问题标题】:is it possible to send the host name on a $resource request?是否可以在 $resource 请求中发送主机名?
【发布时间】:2025-12-15 14:15:02
【问题描述】:

我正在使用 AngularJS 1.5 和 ngResource。 我有一个对象数组,每个对象都包含一个我想在迭代中向其发送 HTTP GET 请求的 IP 地址。例如:

var arr = [{ip: '127.0.0.1', name: 'myHost'},{ip: '1.2.3.4', name: 'differentHost'}]
arr.forEach(function (obj) { // Send requests to obj.ip });

如果我使用 $http 服务并且只是连接 IP 地址,它就可以正常工作。 但是,我想使用 $resource 服务,因为我有一组操作,但是当我使用 $resource 这样做时,它不会将我的主机名/IP 地址作为参数。

    var Host = $resource('http://:ip:49221/:action', { ip: '@ip' }, {
       status: {method: 'GET', params: {action: 'currentStatus'} }
    });
    Host.status({ip: '1.2.3.4'}).$promise.then(function (res) {
        console.log(res);
    });

我得到:XMLHttpRequest 无法加载 http://:ip:49221/currentStatus

Plunker:http://plnkr.co/edit/d9roMDWEbPpyG5upKSrv?p=preview

我做错了吗?

谢谢

【问题讨论】:

    标签: angularjs ngresource angularjs-1.5


    【解决方案1】:

    根据定义,在 XMLHttpRequest 上,您不能进行跨域请求,但您可以探索一些线索。

    How to configure Angular $resource (ngResource) to pull data from another domain using CORS

    Is it Angular $http.defaults.useXDomain really neccessary in CORS?

    请注意 ie8/9 上存在一些问题: https://github.com/angular/angular.js/issues/2956

    【讨论】: