I am using the Google UserService to get login and logout URLs for my app engine Angular application and am trying to pass the path for the redirect as a query param. This is an example of an Angular URL:
http://localhost:8080/#/dashboard
In Java I am trying to create the Url like this:
String logoutUrl = UserServiceFactory.getUserService().createLogoutURL(redirectPath);
redirectPath is the query param string "#/dashboard" as expected.
The problem is that the URL that is produced with the included '#' does not work. It just redirects to itself with a new URL. Here is a sample of what the URL looks like that is generated from the UserService:
/_ah/logout?continue=%23%2Fdashboard
If I just pass the string "/" to the endpoint then I get a URL like this:
/_ah/logout?continue=%2F
This works as expected and loads my Angular app at the root document. I would really like to be able to get my UserService URLS to work as expected. Any ideas?
This is the URL that it redirects to from the URL above:
http://localhost:8080/_ah/logout?continue=%23%2Fdashboard#/dashboard
I found a solution to the problem. The UserService works fine if I send the full URL instead of just the resource path. My Angular code now looks like the following. The app will get the login URL and then redirect to the requested URL upon login. This is actually in a service but I simplified the code for StackOverflow.
$http({
url: '/rest/user/login_uri?redirectPath=' + encodeURIComponent($location.absUrl()),
method: 'GET',
contentType: "application/json"
}).success(function (data) {
$window.location.href = data.uri;
}).catch(function (data) {
//Handle failed request....
});
I hope this helps somebody down the road.
Related
login.js file:
const form = document.getElementById('loginForm');
form.addEventListener('submit',async(e)=>{
e.preventDefault();
return await fetch(`localhost:8000/route`, {
method: "get",
headers: {
"Content-Type": "application/json",
},
});
}
app.js file:
app.get('/index',(req,res)=>{
res.render('route.ejs');
})
I only get the rendered html as a response but can't render it.I know that using form submission works.But can anyone plz tell me how to render the page without submitting form?Thank you in Advance.
The reason you get HTML as a response and not rendered because you use an AJAX call when using fetch. It doesn't instruct the browser what to do with that response.
You have few options.
Either when you get the response back you handle it in your callback like so:
return await fetch(`localhost:8000/route`, {
method: "get",
headers: {
"Content-Type": "application/json",
},
}).then(res=> {
let htmlText = await response.text();
document.getElementsByTagName('body')[0].innerHTML(bodyContent);
});
Or in fact if you just want to load a new page from your ejs template, set the window to the new location and browser will automatically render the response. Something like so in your login.js:
document.location.href = "/route_that_returns_html";
Note that since your question is generic you can take one of the above approach. However as your code suggests if you are trying to implement a login then the right way to do it is in following steps:
Let the form submit as usual ( not using ajax/fetch)
On server side using express, execute the login routine to authenticate the user.
If the authentication passes issue a res.redirect() to the authenticated page that renders using ejs or if fails, redirect back to login page with error.
Finally this DigitalOcean Article explains how to use ejs properly and is worth a read.
I have developed simple cart system in laravel for my local client, it has no any issue on my local server but when I publish it on my live server which is infinity free hosting it has multiple issues. When I try to add to cart the product on home page it is showing 404 error, I am using ajax request.
JS CODE:
jQuery.ajax({
url: "/add_to_cart",
method: "post",
data: jQuery('#formAddToCart').serialize(),
success: function(result){}
my home page url is "new_shop/" and when I remove the "/" from my js code url it is working perfectly but then it shows error on my product detail page where I am using same function and the url of product detail page is "product-name" like this without "/"; product detail page add to cart is also not working with "url: "/add_to_cart"," this url. I don't know what the confusion is as it is working perfectly on my local server. I think it may be issue of free hosting. Any assistance will be appreciated.
ROUTE WEB.PHP CODE:
Route::post('add_to_cart',[FrontController::class,'add_to_cart']);
You are doing it in a wrong way from js code.
You should use name for your routes like this
Route::post('/add_to_cart',[FrontController::class,'add_to_cart'])->name('cart.add');
Now call it from the js code like this
jQuery.ajax({
url: "{{route('cart.add')}}",
method: "post",
data: jQuery('#formAddToCart').serialize(),
success: function(result){}
})
As I am not sure you have group for your route or not
You can try this also
jQuery.ajax({
url: "{{URL::to('/add_to_cart')}}",
method: "post",
data: jQuery('#formAddToCart').serialize(),
success: function(result){}
})
And make sure that you are passing csrf token in your form data.
This way you don't need to worry about your methodName as well as your url. You just need to provide a name to your routes
I have a WebApi controller that after I invoke it I want it to redirect me to another site
Here is my c# code
public async Task<HttpResponseMessage> Login(LoginParameters parameters, [FromUri]string returnUrl)
{
//same validations
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("Http://www.google.com");
return response;
}
My javascript code goes like this
'user strict'
var login = function ($scope, $http) {
var parameters = {
userName: userName,
password: password
};
var url = '/api/user/Login';
$http.post(url, parameters);
.then(function(response){
/*some random code that i will remove */
});
};
login.$inject = ['$scope', '$http'];
module.exports = login;
Looking at the chrome console i realise that the http POST call returns httpstatus = 302. Then i see 2 more request to requests to google.com, but my page is not redirected. So what am I doing wrong?
Thanks in advance
When you use $http, this uses an XMLHttpRequest object which does not adjust the location for the user. It will even follow redirects. You have a couple options:
You could return the new location as a field, then in the .then callback, assign window.location to cause a redirect.
You could use a standard form to post to the resource, then the browser would follow the redirects appropriately.
I would recommend you look into angular interceptors. You can "intercept" the response, check the status code, and redirect using window.location or $location. This is pretty flexible so you write the logic in one place.
Edit: this doesn't seem to work because it appears you can't catch a 302. According to this post, it appears the request is redirected automatically and the response you'd get back is from the redirected location. In the OP's post - the response was empty because the OP was redirected to a different domain which resulted in a cross-domain request (so keep this in mind if your redirects will do the same), but a proposed solution was to check the response to see if it contained data from the redirected page.
I am trying to make a request to a SOS service using Openlayers like this (part of the code):
var params = {'service':'SOS','version':'1.0.0','request':'getCapabilities'};
var paramString = OpenLayers.Util.getParameterString(params);
url = OpenLayers.Util.urlAppend(this.url, paramString);
OpenLayers.Request.GET({url: url,
success: this.parseSOSCaps, scope: this,
failure: alert(url)});
}
For some reason the url that I produced in this code is not correct. The failure function, alerts this url:
http://cawa.gfz-potsdam.de:8080/SOS/sos?service=SOS&version=1.0.0&request=getCapabilities
I also tried manually, through my browser to send the request (using the above url) but it doesn't work. I am sure that the host server is correct.
My questions are: what am I doing wrong? Is the above format of the url wrong? What would be the alternative? Perhaps to send the request in XML format?
Thanks
Dimitris
After all I managed to make the above code to work. There is not a bug in the code. The problem was that I haven't included in the allowedHosts of the proxy.cgi (wamp\bin\apache\apache2.2.22\cgi-bin\proxy.cgi) file, the host of the service. After I did it was working perfectly.
I'm using Expressjs as an API and I'm using angular to hit that POST. I would like to respond to the redirect that express is sending. Success from my Angular POST returns a HTML of the page I intend to redirect to but nothing happens on my DOM. I can see that my redirect is working in my network traffic, and that console.log data, below contains the DOM of the redirected page.
How can I refresh the DOM, to reflect this successful POST, or handle the "redirect"?
ANGULAR CODE:
$http({method: 'POST', url: '/login', data:FormData}).
success(function(data, status, headers, config) {
console.log(data)
}).
error(function(data, status, headers, config) {
});
$scope.userName = '';
Expressjs API:
app.post('/login', function(req, res){
var name = req.param('name', null); // second parameter is default
var password = req.param('password', "changeme")
// Lots Authenticationcode
// returns succesfful login
res.redirect('http://localhost:3000/');
}); // end app.post
console.log(data) (from Angular POST success)
returns the HTML of the page I intended to redirect to
AngularJS is meant to work as a client-side framework coupled with (mostly) RESTfull APIs. Your login API isn't supposed to return a HTML, it is supposed to return the instruction to redirect. So in your case you should simply call $location.url('/') in your $http success callback, which would use the Angular router to "redirect" to '/' (the root URL).