【问题标题】:javascript injection $http post method does not workjavascript注入$http post方法不起作用
【发布时间】:2016-07-18 23:56:33
【问题描述】:

所以我正在创建 Google Chrome 扩展程序,起初我是通过内容脚本注入我的 html、angular 和 javascripts。不,我需要自己注射。我做到了!但问题是,当它通过内容脚本注入时,我的登录方法工作得很好,作为回报,我得到了令牌(这就是我需要的),但是当我自己注入时,我的登录功能不再工作,它会抛出这个错误:

XMLHttpRequest 无法加载 http://www.cheapwatcher.com/api/Authenticate。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://anywebsitename.com' 不允许访问。响应的 HTTP 状态代码为 400。

这是我的登录方法(自从更改了注入类型后我没有更改任何内容):

angular.module('app').controller('LoginController', LoginController);

LoginController.$inject = ['$scope', '$http', '$location', '$state'];

function LoginController($scope, $http, $location, $state) {
    $scope.login = function (user) {
        user.grant_type = 'password';
        return $http({
            method: 'POST',
            url: 'http://www.cheapwatcher.com/api/Authenticate',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'Access-Control-Allow-Origin': '*'
            },
            transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            data: user
        }).success(function (result) {
            console.log(result);
            $(".cheap-watcher").fadeOut(1500, function () {                         
                $(".cheap-watcher").fadeIn($state.go("logout"), {}, { location: false }).delay(2000);
            })
        }).error(function (result) {
            console.log(result);
        });      
    };
};

我可以在服务器端不制作 CORS 的情况下做某事吗?因为正如我所说,通过内容脚本注入效果很好

更新!

所以我将登录方法从 $http 更改为 $.ajax。一切都是一样的,只是我写了 $.ajax 并删除了 headers 部分,而不是 $http。在 chrome 源代码控制中,错误是相同的,但现在在提琴手中,我可以看到我的请求成功。这怎么可能?

现在登录方法如下:

angular.module('app').controller('LoginController', LoginController);

LoginController.$inject = ['$scope', '$http', '$location', '$state'];

function LoginController($scope, $http, $location, $state) {
    $scope.login = function (user) {
        user.grant_type = 'password';
        return $.ajax({
            url: "http://www.cheapwatcher.com/api/Authenticate",
            crossDomain: true,
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            method: 'POST',
            transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            data: user
        }).success(function (result) {
            console.log(result);
            $(".cheap-watcher").fadeOut(1500, function () {
                $(".cheap-watcher").fadeIn($state.go("logout"), {}, { location: false }).delay(2000);
            })
        }).error(function (result) {
            console.log(result);
        });
    };
};

更新 NR。 2!

我看到错误来自http://anywebsitename.com 的索引页。所以我假设我的登录请求不是来自我的扩展程序,而是来自网站内容。注入脚本与后台脚本之间是否可以进行任何通信?

【问题讨论】:

    标签: javascript jquery angularjs google-chrome cors


    【解决方案1】:

    看看Requesting cross-origin permissions,你可以将http://www.cheapwatcher.com/api/Authenticate添加到permissions部分。

    通过向清单文件的权限部分添加主机或主机匹配模式(或两者),扩展程序可以请求访问其源之外的远程服务器。

    【讨论】:

    • 如果这么简单就好了...我的权限部分包括 "http://*/*""https:// */*" 所以它应该可以工作。 - @haibaraAi
    • @NikasŽalias,你最好把你的ajax调用放在后台脚本中,如果你声明了权限,它就不会被同源策略阻止。您可以查看官方指南Message Passing,了解有关内容脚本和后台页面之间通信的更多信息
    【解决方案2】:

    要在 Angular 中使用 CORS,我们需要告诉 Angular 我们正在使用 CORS。我们使用 .config() Angular 应用模块上的方法来设置两个选项。

    1. 我们需要告诉 Angular 使用 XDomain 和
    2. 我们必须从所有请求中删除 X-Requested-With 标头

      angular.module('myApp')
       .config(function($httpProvider) {
          $httpProvider.defaults.useXDomain = true;
          delete $httpProvider.defaults.headers
                  .common['X-Requested-With'];
      });
      

    【讨论】:

    • XMLHttpRequest 无法加载 cheapwatcher.com/api/Authenticate。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'anywebsitename.com' 不允许访问。 仍然是同样的错误 - @adityasingh
    • 您的服务器是否允许来自该域的请求?
    • 是的,它允许 - @AdityaSingh
    猜你喜欢
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多