Javascript 通过POST或GET请求头将授权数据从Angular传递到NodeJS服务器
一方面,我使用gulp watch在本地运行端口9000 另一方面,我有一个运行在3000端口上的nodejs服务器 在本文中,我使用以下代码发布/获取Javascript 通过POST或GET请求头将授权数据从Angular传递到NodeJS服务器,javascript,angularjs,node.js,http-headers,Javascript,Angularjs,Node.js,Http Headers,一方面,我使用gulp watch在本地运行端口9000 另一方面,我有一个运行在3000端口上的nodejs服务器 在本文中,我使用以下代码发布/获取 $scope.click = function(){ console.log("clicked"); var req = { method: 'POST', url: 'http://localhost:3000/hello?ids=1,2,3', // headers: { // 'Con
$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);
} );
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);
});
当单击函数在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 browser页面上,我得到:
clicked
SUCCESS! With data: Object {someData: "to send back to Angular"}
And status: 200
这很好,但只要我尝试通过从角度向标题添加更多元素来更改标题,所有内容都将转到Pete Tong
因此,我需要包括哪些修改,以便将授权信息(如令牌)从Angular传递到两侧的NodeJ,以允许它们成功通过
谢谢你的帮助。@Jules谢谢你
$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);
} );
首先,成功处理程序只返回数据,但不会返回给getData的调用方,因为它已经在回调中$http是一个异步调用,返回$PROMITE,因此当数据可用时,必须注册回调 我建议在AngularJS中查找Promissions和$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实际上已经返回了$PROMITE,因此可以重新编写:
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文档以获取示例
$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' );
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);
} );
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'一部分的节点上的授权
然后在角度方面,只需使用授权设置标题即可将信息成功地传递给Nodejs。您应该使用get方法…@RavindraGalav感谢您的简短回答,但请您详细说明一下,因为我也尝试过get。谢谢。谢谢。但是您的答案如何处理自定义标题信息以包括令牌?请将这些作为查询传递给URL,使其在URL上可见谢谢您的回答。我仍然无法看到您的解决方案是如何传递自定义头信息的?我看到查询被传递,身体数据已经在我设计的版本中工作。但问题是关于传递自定义标题,如授权或类似“X-custom-data”的自定义标题:“‘任何数据’但在标题中……亲爱的Ravindra,感谢您的建议,我设法找到了解决问题的方法,如我的解决方案中所述,通过向setHeader添加授权。信息现在已成功传递,因此那里的一切都很好。再次非常感谢你的帮助,并为我的迟到表示歉意,我当时正在四处旅行。