我试图通过连接到Flask内置的RESTful API来使用JavaScript进行授权.但是,当我发出请求时,我收到以下错误:
XMLHttpRequest无法加载http:// myApiUrl/login.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许原点'null'访问.
我知道API或远程资源必须设置标题,但为什么在我通过Chrome扩展程序Postman发出请求时它可以正常工作?
这是请求代码:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
Run Code Online (Sandbox Code Playgroud) 我使用JavaScript为Flickr照片搜索API创建了一个演示.现在我将它转换为AngularJs.我在互联网上搜索,发现下面的配置.
组态:
myApp.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
Run Code Online (Sandbox Code Playgroud)
服务:
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.flickrPhotoSearch = function() {
return $http({
method: 'GET',
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=3f807259749363aaa29c76012fa93945&tags=india&format=json&callback=?',
dataType: 'jsonp',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
Run Code Online (Sandbox Code Playgroud)
控制器:
myApp.controller('flickrController', function($scope, dataService) {
$scope.data = null;
dataService.flickrPhotoSearch().then(function(dataResponse) {
$scope.data = dataResponse;
console.log($scope.data);
});
});
Run Code Online (Sandbox Code Playgroud)
但我仍然得到同样的错误.以下是我尝试的一些链接:
XMLHttpRequest无法加载URL.Access-Control-Allow-Origin不允许原点
http://samurails.com/tutorial/cors-with-angular-js-and-sinatra/
编辑:
我在@Quentin的建议下在node.js中创建了一个代理服务器:
var http = require('http');
var url = require('url');
var fs = require('fs');
var server;
server = http.createServer(function (req, res) {
// your normal server …Run Code Online (Sandbox Code Playgroud) AngularJS文档有关于$http success和error方法的弃用通知.这个抽象是从库中删除的具体原因吗?
我从node.js服务器获取数据时遇到问题.
客户端是:
public getTestLines() : Observable<TestLine[]> {
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://localhost:3003/get_testlines', options)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
Run Code Online (Sandbox Code Playgroud)
在服务器端我也设置了标题:
resp.setHeader('Access-Control-Allow-Origin','*')
resp.send(JSON.stringify(results))
Run Code Online (Sandbox Code Playgroud)
但是我收到了一个错误
"XMLHttpRequest无法加载http:// localhost:3003/get_testlines.对预检请求的响应未通过访问控制检查:请求的资源上没有'Access-Control-Allow-Origin'标头.来源' http://因此不允许localhost:3000 '访问."
我该如何解决?当我删除标题时,它表示此标题是必需的.
CORS 在服务器上很好,并且按预期工作。我尝试使用 angular HTTPClient 向服务器的 REST API 发送请求,但收到 CORS 错误。如果在服务器上启用了 CORS,为什么会出现此错误?客户端应该没问题吧?
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/blah/blah (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Run Code Online (Sandbox Code Playgroud)
编辑://修复...和//下面代码中的错误评论显示答案
对于JavaScript专家来说,这可能是一件愚蠢而且显而易见的事情......但如果我能看到这一点,我将会受到威胁.
这是我的t.js:
var angularApp = angular.module('myApp', []);
angularApp.controller('mainController', ['$scope', '$http', '$log',
function ($scope, $http, $log) {
$scope.version = angular.version;
var ctime = new Date();
$scope.ctime = ctime.getTime() / 1000;
$http.get('http://127.0.0.1:8765/').then(
function(res){
$scope.stime = res['data']['server-time'] / 1000;
// Fix goes here: $scope.skew = $scope.stime - $scope.ctime;
},
function(error){
$log.warn('Unable to get time');});
// Error here: this happens asynchronously to the $http.get!
$scope.skew = parseFloat($scope.stime) - parseFloat($scope.ctime);
}]);
Run Code Online (Sandbox Code Playgroud)
...和我的HTML:
<!DOCTYPE html>
<html lang="en-us" data-ng-app="myApp"><head><title>Time Skew</title>
<meta charset="UTF-8">
<link rel="stylesheet" …Run Code Online (Sandbox Code Playgroud) angularjs ×3
cors ×3
javascript ×3
angular ×2
express ×1
html ×1
http-headers ×1
jquery ×1
node.js ×1