I am using Revel + angular for my application. The index page is the login interface, and once you are successful, you should be directed to the dashboard.html page. The problem is once I have made a POST request, I get a GET request with my 'response body', however, I am still in the login page. I am using angular to make a post request to my restful server. However, whenever I make a POST request I get status 302 on my POST request but my GET request fetches the response for the page.
My Angular Controller
appMainLogin.controller('MainLoginForm',function($scope, $http){
$scope.user_email = null;
$scope.user_pass = null;
$scope.user_remember = true;
$scope.userLogin = function () {
var val = {
"user_email": $scope.user_email,
"user_pass": $scope.user_pass,
"user_remember": $scope.user_remember,
};
var stringify = JSON.stringify(val);
$http({
url: '/login',
method: 'POST',
data: stringify || '',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}
}).success($scope.getEmailData).error($scope.httpError);
alert("error");
};
});
My routes
POST /login App.Login
GET /dash Dash.Index
I get this: 302 on the POST request
I get this: 200 OK on the GET request
On the 'response body' of the GET request (firefox debugger) I see my I intended html page but I still remain in the index page.
Why is my app not redirecting to the dashboard.html(index.html->dashboard.html) after the user enters their login credential (based on my code above)?
Related
I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});
I'm working on nodejs loopback application. I've a user logged in already and and an operation requires this user to find a userById and update a field.
$scope.user = User.findById({
id: sender.id
});
$scope.user.supplierId = currUserId;
$scope.user.$save();
But its not working as required.
and I get following error:
PUT http://localhost:5000/api/users 401 (Unauthorized)
GET http://localhost:5000/api/AuthProviders/count 401 (Unauthorized)
401 while on router on login path
POST http://localhost:5000/api/users/login?include=user 400 (Bad Request)
Any help will be appreciated.
Thanks
For findById operation:
var url = 'http://localhost:3000/api/User/' + sender.id + '?access_token=h9vpJ94zqN199ENWx'
$http({
method: 'GET',
url: url
}).then(function successCallback(response) {
console.log(response);
}, function errorCallback(error) {
throw error;
});
Otherwise you can use Angular SDK which makes it much cleaner.
I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?
Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token
I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;
I am facing a weird issue. I am running my angularjs app in nodejs server locally which calls a POST API from my app located on Google App Engine. The API is configured with all CORS headers required as follows:
def post(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.headers.add_header("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS")
self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With, content-type, accept, myapp-domain")
self.response.headers["Content-Type"] = “application/json; charset=utf-8”
GET requests to the API work without issues.
POST requests to the API work but ONLY when I send the post data as a 'string of params' and NOT when post data is sent as an object which is the right way to do. Eventually I need to be able to upload pictures using this API so the first solution below might not work for me. Please help!
METHOD 1: This works:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = "conversationid=1c34b4f2&userid=67e80bf6&content='Hello champs! - Web App'";
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz",
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
METHOD 2: This fails:
postMessageAPI = "https://myapp-qa.appspot.com/message";
var postData = ({
'conversationid' : '1c34b4f2',
'userid' : '67e80bf6',
'content' : 'Hello champs! - Web App'
});
var postConfig = {
headers: {
"MYAPP-DOMAIN" : "myapp.bz"
'Content-Type': 'application/json; charset=UTF-8'
}
};
$http.post(postMessageAPI, postData, postConfig).
success(function(data){
$log.log("POST Message API success");
}).
error(function(data, status) {
$log.error("POST Message API FAILED. Status: "+status);
$log.error(JSON.stringify(postData));
});
When I use METHOD 2 it fails with the following error in the console:
XMLHttpRequest cannot load https://myapp-qa.appspot.com/message.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://0.0.0.0:8000' is therefore not allowed access.
Please let me know if you have any solution. Thanks in advance.
The issue is most likely with Angular sending a pre-flight OPTIONS request to check the access headers from the server. I am not sure how OPTIONS requests are handled in your API, but I am betting these headers are not being added. I suggest installing Fiddler to monitor the actual requests to see what is going on with the headers. You may only be adding them to your POST responses.
See this answer for details on why METHOD 1 may work in this scenario, while METHOD 2 does not.
Here are some more details about pre-flight requests.
I have a http get request from client angular to server
If the request returns a 404, the app gets redirected to the default page which is my home page.
How do I prevent the redirect on the error function handle therE?
$http({
method: 'POST',
url: '/customers/' + customer.id + "/addresses",
data: address
})
.success(function(address){
})
.error(function(data){
//prevent the 404 redirect here
});