一方面,我使用gulp watch
通过端口9000在本地运行Angular另一方面,我在端口3000上运行了一个nodejs服务器。
在Angular中我使用以下代码进行POST / GET。
$scope.click = function(){
console.log("clicked");
var req = {
method: 'POST',
url: 'http://localhost:3000/hello?ids=1,2,3',
// headers: {
// 'Content-Type': 'text/plain'
// ,'Authorization' : 'Basicbulletproof'
// },
data: {
something: "some_data"
}
};
success( function( data, status, headers, config ) {
// something called here
console.log( "SUCCESS! With data: ", data );
console.log( "And status: ", status );
}).
error( function( data, status, headers, config ) {
// something called here
console.log( "ERROR! With data: ", data );
console.log( "And status: ", status );
});
};
在我的节点服务器上,我有:
app.all( '/*', function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type' );
next();
});
app.post('/hello', function ( req, res ) {
console.log( "HEADER: ", req.headers );
console.log( "QUERY: ", req.query );
console.log( "BODY: ", req.body );
var metrics = {someData: "to send back to Angular"};
res.send(metrics);
} );
当点击功能通过Angular运行时,在NodeJS端我得到以下内容:
OPTIONS /hello?ids=1,2,3 200 15.265 ms - 13
HEADER: { host: 'localhost:3000',
connection: 'keep-alive',
'content-length': '49',
accept: 'application/json, text/plain, */*',
origin: 'http://localhost:9000',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36',
'content-type': 'application/json;charset=UTF-8',
referer: 'http://localhost:9000/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-US,en;q=0.8' }
QUERY: { ids: '1,2,3' }
BODY: { something: 'some_data' }
POST /hello?ids=1,2,3 200 6.073 ms - 22
在Angular浏览器页面上,我得到了:
clicked
SUCCESS! With data: Object {someData: "to send back to Angular"}
And status: 200
这一切都很好,但是一旦我尝试通过从Angular添加更多元素来改变标题,它就会变成Pete Tong ......
因此,我需要进行哪些修改才能将授权信息(如Angular中的令牌)传递给NodeJS,以便成功通过?
感谢您的帮助。
答案 0 :(得分:0)
@Jules for angular
$scope.click=function(){
$http.post("http://localhost:3000/hello"+ids+"").success(function(data){
//console.log(data);
$scope.load=angular.fromJson(data);
}).error(function(){alert("Error");
});
}
和节点服务器
app.all( '/*', function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type' );
next();
});
app.post('/hello/:ids', function ( req, res ) {
//console.log( "HEADER: ", req.headers );
console.log( "QUERY: ", req.param.ids );
// console.log( "BODY: ", req.body );
var metrics = {someData: "to send back to Angular"};
res.send(metrics);
} );
答案 1 :(得分:0)
首先,你的success()处理程序只返回数据,但是它没有返回给getData()的调用者,因为它已经在回调中了。 $ http是一个返回$ promise的异步调用,因此您必须在数据可用时注册回调。
我建议在AngularJS中查找Promises和$ q库,因为它们是传递服务之间异步调用的最佳方式。
为简单起见,这里是用调用控制器提供的函数回调重写的相同代码:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData(function(dataResponse) {
$scope.data = dataResponse;
});
});
现在,$ http
实际上已经返回$ promise,因此可以重写:
var myApp = angular.module('myApp',[]);
myApp.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function() {
// $http() returns a $promise that we can add handlers with .then()
return $http({
method: 'GET',
url: 'https://www.example.com/api/v1/page',
params: 'limit=10, sort_by=created:desc',
headers: {'Authorization': 'Token token=xxxxYYYYZzzz'}
});
}
});
myApp.controller('AngularJSCtrl', function($scope, dataService) {
$scope.data = null;
dataService.getData().then(function(dataResponse) {
$scope.data = dataResponse;
});
});
最后,有更好的方法来配置$ http
服务,以便使用config
()设置$ httpProvider
来处理标头。查看$ http
文档以获取示例。
答案 2 :(得分:0)
$scope.click = function(){
console.log("clicked");
var req = {
method: 'POST',
url: 'http://localhost:3000/hello?ids=1,2,3',
headers: {
'Authorization' : 'Basicbulletproof'
},
data: {
something: "some_data"
}
};
success( function( data, status, headers, config ) {
// something called here
console.log( "SUCCESS! With data: ", data );
console.log( "And status: ", status );
}).
error( function( data, status, headers, config ) {
// something called here
console.log( "ERROR! With data: ", data );
console.log( "And status: ", status );
});
};
在我的节点服务器上,我有:
app.all( '/*', function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization' );
next();
});
app.post('/hello', function ( req, res ) {
console.log( "HEADER: ", req.headers );
console.log( "QUERY: ", req.query );
console.log( "BODY: ", req.body );
var metrics = {someData: "to send back to Angular"};
res.send(metrics);
});
正如您所看到的,我错过了"授权"在节点上作为res.setHeader的一部分(' Access-Control-Allow-Headers',...
然后在Angular方面,只需使用Authorization设置Header就可以将信息成功传递给Nodejs。