我有这个jQuery代码,可以很好地交叉起源:
jQuery.ajax({
url: "http://example.appspot.com/rest/app",
type: "POST",
data: JSON.stringify({"foo":"bar"}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log("success");
},
error: function (response) {
console.log("failed");
}
});
Run Code Online (Sandbox Code Playgroud)
现在我想把它转换成Angular.js代码而没有任何成功:
$http({
url: "http://example.appspot.com/rest/app",
dataType: "json",
method: "POST",
data: JSON.stringify({"foo":"bar"}),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
}).success(function(response){
$scope.response = response;
}).error(function(error){
$scope.error = error;
});
Run Code Online (Sandbox Code Playgroud)
任何帮助赞赏.
我知道有很多这样的问题,但我见过的都没有解决我的问题.我已经使用过至少3个微框架.所有这些都在进行简单的POST时失败,这应该返回数据:
angularJS客户端:
var app = angular.module('client', []);
app.config(function ($httpProvider) {
//uncommenting the following line makes GET requests fail as well
//$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
app.controller('MainCtrl', function($scope, $http) {
var baseUrl = 'http://localhost:8080/server.php'
$scope.response = 'Response goes here';
$scope.sendRequest = function() {
$http({
method: 'GET',
url: baseUrl + '/get'
}).then(function successCallback(response) {
$scope.response = response.data.response;
}, function errorCallback(response) { });
};
$scope.sendPost = function() {
$http.post(baseUrl + '/post', {post: 'data from client', withCredentials: true })
.success(function(data, status, headers, config) …Run Code Online (Sandbox Code Playgroud) 我有使用jQuery CORS和自定义Content-type发送AJAX正文请求的问题.这是我的代码:
$.ajax({
url: "http://some-other-domain/my-path",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
key: 1,
key2: 2
}),
statusCode: {
200: function(data) {
}
},
xhrFields: {
withCredentials: true
},
crossDomain: true
});
Run Code Online (Sandbox Code Playgroud)
我需要将Content-type设置为"application/json",因为它需要服务器端.但不是发送请求作为POST jQuery发送它作为OPTIONS.
这是一个标题:
响应标题:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Pragma: No-cache
Cache-Control: no-cache
Expires: Thu, 01 Jan 1970 03:00:00 EET
Set-Cookie: JSESSIONID=BB9D6783E58FB0F2ADE1924A2F0CBA52; Path=/
Content-Type: text/html;charset=UTF-8
Content-Length: 6233
Date: Fri, 07 Sep 2012 14:41:13 GMT
Run Code Online (Sandbox Code Playgroud)
请求标题:
OPTIONS /my-path HTTP/1.1
Host: MY-HOME-NAME
User-Agent: MY_USER_AGEMT
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: …Run Code Online (Sandbox Code Playgroud) 我在Postman中尝试了以下代码并且它正在工作.代码有问题吗?
$.ajax({
url: 'http://api.example.com/users/get',
type: 'POST',
headers: {
'name-api-key':'ewf45r4435trge',
},
data: {
'uid':36,
},
success: function(data) {
console.log(data);
}
});
Run Code Online (Sandbox Code Playgroud)
我在我的控制台中收到如下错误,请指教.
XMLHttpRequest无法加载http://api.example.com/users/get预检的响应无效(重定向)
我正在尝试为我的angular2应用添加基本身份验证.
public login() {
// Set basic auth headers
this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + this.password));
console.log('username', this.username)
console.log('password', this.password)
console.log(this.defaultHeaders)
// rest is copy paste from monbanquetapiservice
const path = this.basePath + '/api/v1/development/order';
let req = this.http.get(path, { headers: this.defaultHeaders });
req.subscribe(
_ => { },
err => this.onError(err)
);
}
Run Code Online (Sandbox Code Playgroud)
我期望看到的是带有Authorization我放置的标题的GET请求.
但我看到的首先是带有此标题的OPTIONS:
OPTIONS /api/v1/development/order HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X …Run Code Online (Sandbox Code Playgroud) 在AngularJS中,有$http.get动态获取数据.遗憾的是,从官方文档中不易理解如何读取二进制数据(例如,用于图像处理).
默认值get将数据提取为a String(在plunker中查看).这非常麻烦.那么,如何在ArrayBuffer中获取它?(注意,因为XHR2 已经可以了.)
<!DOCTYPE html>
<html>
<head>
<title>Using $http.get to read binary data</title>
</head>
<body ng-app>
<h1>$http to load binary data</h1>
<div ng-controller="FetchCtrl" >
<button ng-click="fetch()">fetch</button><br/>
{{info}}
</div>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<script>
// Controller
function FetchCtrl($scope, $http) {
// See note 1
$scope.URL = "http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png";
$scope.info = "Click 'fetch' to fetch an image" ;
$scope.fetch = function() {
delete $http.defaults.headers.common['X-Requested-With']; // See note 2
$http.get($scope.URL).
success(function(data) {
$scope.info …Run Code Online (Sandbox Code Playgroud) 我正在编写一个简单的库应用程序,以便为使用AngularJS的大型项目做好准备.在网上阅读了很多关于使用$resource与RESTful API交互的内容之后,我认为它可能会提供一些节省时间和扩展的好处来实现它而不是$http用于每个请求.问题是,由于某种原因(我不是CORS的专家,并且请求是跨域发送的),在使用$save我的Node.js控制台显示的方法时:
OPTIONS /books 200 1ms - 161b
Run Code Online (Sandbox Code Playgroud)
使用该query()方法工作正常 - 节点控制台显示:
GET /books 200 1ms - 228b
Run Code Online (Sandbox Code Playgroud)
此时我已经被困了几个小时,尝试下面的变化,但它总是最终成为OPTIONS请求而不是POST(这应该是根据Angular文档应该是该$save方法).
app.js
var libraryApp = angular.module('libraryApp', ['ngResource', 'ngRoute', 'libraryControllers']);
libraryApp.factory('$book', ['$resource', function ($resource) {
return $resource('http://mywebserver\\:1337/books/:bookId', { bookId: '@bookId' });
}]);
Run Code Online (Sandbox Code Playgroud)
controllers.js
var libraryControllers = angular.module('libraryControllers', []);
libraryControllers.controller('BookCtrl', ['$scope', '$book', function($scope, $book) {
...
$scope.addBook = function () {
var b = new $book;
b.isbn = "TEST";
b.description = "TEST"; …Run Code Online (Sandbox Code Playgroud) 我无法将Angular前端与Rails后端API完全集成.它们都运行在不同的服务器上,所以我认为我的CORS存在问题.
我的Angular应用程序正在运行一个控制器,该控制器正在调用具有查询(GET)和保存(POST)方法的资源的服务.查询(GET)工作正常,但帖子不起作用.
当我不发送任何参数时,我能够向服务器发送POST请求.像这样:
控制器:
$scope.createBusiness = function() {
console.log("Business.name=" + $scope.business.name);
$scope.business = Business.save();
};
Run Code Online (Sandbox Code Playgroud)
服务:
.factory('Business',
function($resource){
var businesses =
$resource('http://127.0.0.1\\:3000/:business', {business:'businesses'}, {
query: {method:'GET', isArray: true},
save: {method:'POST', isArray: false}
});
return businesses;
}
Run Code Online (Sandbox Code Playgroud)
);
但是,我想发布我的模型参数,所以当我尝试发送内容时,我不再发送POST请求,而是发送OPTIONS请求.我收到一个错误.
请在发送不带参数的请求时查看我的请求数据(POST请求):
Request URL:http://127.0.0.1:3000/businesses
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:es-ES,es;q=0.8
Connection:keep-alive
Content-Length:0
Content-Type:text/plain;charset=UTF-8
Host:127.0.0.1:3000
Origin:http://localhost:1234
Referer:http://localhost:1234/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept, …Run Code Online (Sandbox Code Playgroud) 我尝试从我的角度登录服务POST:
$http.post('https://xyz/login',
{
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'signature': 'asd'
}
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
XMLHttpRequest cannot load https://xyz/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1337' is therefore not allowed access.
Run Code Online (Sandbox Code Playgroud)
我试过这个标题:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
Run Code Online (Sandbox Code Playgroud)
还有这些:
"Access-Control-Allow-Origin": "*";
"Access-Control-Allow-Headers": "X-Requested-With";
"Access-Control-Allow-Methods": "GET, POST", "PUT", "DELETE";
Run Code Online (Sandbox Code Playgroud)
有趣的是,POSTMAN是有效的.我该怎么办?
谢谢.
我有一个Rails服务返回我的AngularJS前端应用程序的数据.该服务配置为通过返回足够的头来允许CORS请求.
当我发出接收数据的GET请求时,会发送CORS标头,以及我以前在登录时收到的会话cookie,您可以自己查看:
Request URL:http://10.211.194.121:3000/valoradores
Request Method:GET
Status Code:200 OK
Request Headers
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:_gestisol_session=BAh7B0kiDHVzZXJfaWQGOgZFRmkASSIPc2Vzc2lvbl9pZAY7AEZJIiVmYTg3YTIxMjcxZWMxNjZiMjBmYWZiODM1ODQzMjZkYQY7AFQ%3D--df348feea08d39cbc9c817e49770e17e8f10b375
Host:10.211.194.121:3000
Origin:http://10.211.194.121:8999
Pragma:no-cache
Referer:http://10.211.194.121:8999/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
X-Requested-With:XMLHttpRequest
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With,X-Prototype-Version,Content-Type,Cache-Control,Pragma,Origin
Access-Control-Allow-Methods:GET,POST,OPTIONS
Access-Control-Allow-Origin:http://10.211.194.121:8999
Access-Control-Max-Age:1728000
Cache-Control:max-age=0, private, must-revalidate
Connection:Keep-Alive
Content-Length:5389
Content-Type:application/json; charset=utf-8
Date:Mon, 04 Nov 2013 14:30:51 GMT
Etag:"2470d69bf6db243fbb337a5fb3543bb8"
Server:WEBrick/1.3.1 (Ruby/1.9.3/2011-10-30)
X-Request-Id:15027b3d323ad0adef7e06103e5aa3a7
X-Runtime:0.017379
X-Ua-Compatible:IE=Edge
Run Code Online (Sandbox Code Playgroud)
一切都是正确的,我得到了我的数据.
但是当我发出POST请求时,CORS头和会话cookie都不会沿请求发送,并且POST在服务器上被取消,因为它没有会话标识符.这些是请求的标头:
Request URL:http://10.211.194.121:3000/valoraciones
Request Headers
Accept:application/json, text/plain, */*
Cache-Control:no-cache
Content-Type:application/json;charset=UTF-8
Origin:http://10.211.194.121:8999
Pragma:no-cache
Referer:http://10.211.194.121:8999/
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, …Run Code Online (Sandbox Code Playgroud) angularjs ×7
cors ×6
ajax ×4
javascript ×4
jquery ×3
cross-domain ×2
angular ×1
angular-http ×1
cookies ×1
express ×1
http ×1
ngresource ×1
node.js ×1
php ×1
session ×1