How to redirect to url within same context - vert.x

I have /logout action, that should redirect to /login. /login renders template, where I read flash message from context. This works, but url in browser is still remains "/logout":
router.get("/logout").handler((ctx) => {
if (ctx.user()!=null) {
ctx.clearUser()
//flash message
ctx.put("msg", "Logout succeed")
}
ctx.reroute("/login")
})
What I want, but url should be "/login":
Better to use(?):
ctx.response.putHeader("location", "/login").setStatusCode(302).end()
But there is different context. So I haven't flash message.
How to redirect to /login within same context?
Upd.
Question related to this issue

In order to work with flash messages you should add a cookie to the redirect with the content:
// this makes the message available to the client
ctx
.addCookie(Cookie.cookie("flashMessage", "Logout succeed"));
// configure where to redirect
ctx.response()
.putHeader("location", "/login");
// perform the redirect
ctx.end(302);
Then on the client side you need a bit of JavaScript to read the message and
perform the display as you wish. Since there is no simple way to read cookies on the browser if you're using jQuery with the cookie plugin you can do something like:
$.fn.flashMessage = function (options) {
var target = this;
options = $.extend({}, options, { timeout: 3000 });
if (!options.message) {
options.message = getFlashMessageFromCookie();
deleteFlashMessageCookie();
}
if (options.message) {
if (typeof options.message === "string") {
target.html("<span>" + options.message + "</span>");
} else {
target.empty().append(options.message);
}
}
if (target.children().length === 0) return;
target.fadeIn().one("click", function () {
$(this).fadeOut();
});
if (options.timeout > 0) {
setTimeout(function () { target.fadeOut(); }, options.timeout);
}
return this;
function getFlashMessageFromCookie() {
return $.cookie("FlashMessage");
}
function deleteFlashMessageCookie() {
$.cookie("FlashMessage", null, { path: '/' });
}
};
And add a placeholder in your HTML like:
<div id="flash-message"></div>
And trigger it like:
$(function() {
$("#flash-message").flashMessage();
});

Related

how to send post data with inappbrowser ionic 4

I need to know how you can send data by post via inappbrowser to an external url that is a payment gateway
I am dealing with the property of ionic execute Script however I have not managed to pass the post data, I would like to see if there is another way but I need to use inappbrowser
let options: InAppBrowserOptions={
zoom:'no',clearcache:'yes',hidden:'yes',hidenavigationbuttons:'yes',hideurlbar:'yes'
};
let customheader= 'foo:123,bar:456';
const browser= this.iab.create('https://url_anyway','_blank',options);
browser.on('loadstop').subscribe( (ev: InAppBrowserEvent) => {
browser.executeScript({code: "(function() {const data = new FormData(document.getElementById('mp_account'));fetch('https://url_anyway', { method: 'POST', body: data}).then(function(response) { if(response.ok) { return response.text() } else { throw 'Error en la llamada Ajax';}}).then(function(texto) { console.log(texto);}).catch(function(err) { console.log(err);}); })()"}).then( function(){
setTimeout(function(){
browser.show();
;}, 1500);
});
});
when opening the url does not show anything by post method

Redirect Doesn't Allow Me To Go To Other Links

I am trying to make a login redirect using the following code:
Router.onBeforeAction(function () {
if (!Meteor.user() && !Meteor.loggingIn()) {
this.next();
} else {
// required by Iron to process the route handler
this.redirect('/map');
this.next();
}
});
But, when I login and it successfully redirects me to /maps, I can't click any of my link on my navbar. The link are working fine, but, when I click on them it just redirects me back to /map.
Help will be much appreciated!
Also, here is the github link:
https://github.com/Aggr0vatE/testbasichelp
What about this:
Router.route('/login',
{ name: 'login' });
var requireLogin = function(){
if (! Meteor.user() ) {
this.redirect('login');
} else {
this.next();
}
}
Router.onBeforeAction(requireLogin, {except: ['login']});

Codeigniter-restserver does not accept POST method CORS

I'm developing a REST API using Codeigniter-restserver for a mobile applications in Phonegap.
Since Phonegap loads index.html using file://, my API should support CORS. And I'm new to this CORS.
I've set headers in libraries/REST_Controller.php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept');
And I'm using Backbone.js.
Here is my Controller
// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';
class Prop extends REST_Controller
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
function property_get()
{
...
}
function property_post()
{
...
}
function attach_image($file_type)
{
if($this->post($file_type) != ""){
save_base64_image($file_type,$this->post($file_type));
$this->email->attach($_SESSION[$file_type]);
}
}
function property_delete()
{
...
}
function share_post()
{
$email_id = $this->post('emailid');
$config['mailtype'] = "html";
$this->email->initialize($config);
$this->email->from('myid#gmail.com', 'mobile app');
$this->email->to($email_id);
$this->email->subject('subject');
$this->email->message('message');
if ( ! $this->email->send() )
{
$this->response("Internal server error.", 500);
}
else
{
$result = new stdClass();
$result->message = 'Email has been sent.';
$this->response($result, 200); // 200 being the HTTP response code
}
}
public function send_post()
{
var_dump($this->request->body);
}
public function send_put()
{
var_dump($this->put('foo'));
}
}
Here's my jQuery ajax call.
$.ajax( {
url: PMSApp.apiUrl + "/share/format/json",
type: 'post',
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(function(response) {
console.log(JSON.stringify(response));
})
.fail(function(response) {
console.log(JSON.stringify(response));
})
.always(function(response) {
console.log(JSON.stringify(response));
});
I'm able to access this /share/format/json API with POSTMAN, chrome extension, but not with file:// or localhost://.
EDIT:
I've also tried changing share_post() to share_gett(), It worked. But i need it in POST.
I'm stuck on this for the past 48 hours. Tried many solutions, but nothing helped me with this issue. Please help me.
Phonegap provides option to whitelist your webservice domain. It is set up the access origin in config xml
http://docs.phonegap.com/en/2.3.0/guide_whitelist_index.md.html
You have to start Chrome with Access-Control-Allow-Origin
This thread:
https://superuser.com/questions/384871/overriding-access-control-allow-origin-restriction-in-google-chrome
Check this tread:
Origin is not allowed by Access-Control-Allow-Origin

How to serve 404's using AngularJS and a RESTful API

Let's say you have an AngularJS application hooked up to a RESTful API and you have a route for "/item/:itemId".
.when('/item/:itemId', {
templateUrl: '/static/partials/item-detail.html',
controller: ItemDetailController
})
angular.module('angServices', ['ngResource']).factory('Item', function($resource) {
return $resource('/api/item/:itemId', {}, {
query: { method: 'GET', params: { itemId: '' }, isArray: true }
});
});
If the user goes to "/item/9" and an object with the itemId 9 does not exist, Angular will receive a 404 from the API, but will not naturally return a 404 to the user.
In other questions, I've seen people suggest creating an interceptor and having Angular redirect to a 404 error page when a resource is not found.
var interceptor = ['$rootScope', '$q', function(scope, $q) {
...
function error(response) {
if (response.status == 404) { window.location = '/404'; }
...
$httpProvider.responseInterceptors.push(interceptor);
However, I want to return a correct 404 with the original requested URL for SEO purposes.
Also, the solution above first loads the page and then redirects (just like Twitter used to do), so its sub-optimal.
Should I check server-side to first see if the resource exists before passing the request on to the Angular app? The downside of this is that it wouldn't work for broken links within the application.
What is the best way to approach this?
Maybe this jsfiddle can help you.
http://jsfiddle.net/roadprophet/VwS2t/
angular.module('dgService', ['ngResource']).factory("DriveGroup", function ($resource) {
return $resource(
'/', {}, {
update: {
method: 'PUT'
},
fetch: {
method: 'GET',
// This is what I tried.
interceptor: {
response: function (data) {
console.log('response in interceptor', data);
},
responseError: function (data) {
console.log('error in interceptor', data);
}
},
isArray: false
}
}
);
});
var app = angular.module('myApp', ['ngResource', 'dgService']);
app.controller('MainController', ['$scope', 'DriveGroup', function ($scope, svc) {
$scope.title = 'Interceptors Test';
svc.fetch(function (data) {
console.log('SUCCESS');
}, function () {
console.log('FAILURE');
});
}]);
I tried with this and works fine. I only change the fetch method to get.
In your case, you will need to change the console.log('FALIURE'); to $location.path('/404');.
GL!

Jquery, Validate, Submit Form to PHP (Ajax Problem)

Very early days playing Javascript, Jquery and Validate.
I am using the Submit Button onClick method for form submission.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using the submit, in case no data or not every field has been tested.
The logic is working, but the AJAX call does not appear to be working. I have stripped down the PHP to
<?php
touch('phpTouch.txt');
phpinfo();
sleep(30;)
?>
The javascript is
$(document).ready(function () {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
dataType: "json",
success: function () {
alert("SUCCESS:");
},
error: function () {
alert("ERROR: ");
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
return false; // Prevent the default SUBMIT function occurring (is this a fact ??)
};
Can anyone advise as to what I am doing wrong.
Thanks
Do these things
Change onClick="submitForm()" on the HTML markup to onclick="submitForm(event)"
Now change the submitForm function like this.
function submitForm(evt) {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').valid() ) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
$.ajax({
url: "testPHP.php",
type: "POST",
data: frmData,
contentType: "application/json;",
success: function () {
alert("SUCCESS:");
},
error: function (a, b, c) {
alert(a.statusText);
}
});
} else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
evt.preventDefault();
};
Please note these things
Check .valid() to determine form validity
Call .preventDefault() instead of return false; ( Its more jQuery-ish )