【发布时间】: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