Adding Authorization to Header - angular6

i'm using Angular 6 and DevExpress Xtra-report module. I want to added Authorization in header.Well i'm using HttpInterceptor to add Authorization and its working good with all my others modules except my xtra-report module so i tried to pass the authorization using jquery inside my module (as shown bellow ) which is not working and i'm not really comfortable with it.
I'm getting the Token inside userId.
const userId = localStorage.getItem('access_token');
$.ajaxSetup({
cache: true,
type: 'POST',
xhrFields: {
withCredentials: true,
Authorization: `Bearer ${userId}`,
},
complete: function (result) {
// console.log('complete');
},
error: function (jqXHR, status, erreur) {
// console.log('error');
},
beforeSend: function (xhr, settings) {
console.log(`beforeSend beforeSend beforeSend beforeSend beforeSend beforeSend + ${userId}`);
xhr.withCredentials = true;
xhr.Authorization = `Bearer ${userId}`;
}
});
I dont know why HttpInterceptor work with all my module except xtra-report module, maybe cause i'm charging it lazy or i dont know , any help would be appreciated, tell me in case of additional informations from my side.
Thank you

i solved this by adding headers with Authorization inside it , so it becomes like this :
const userId = localStorage.getItem('access_token');
$.ajaxSetup({
cache: true,
type: 'POST',
xhrFields: {
withCredentials: true,
},
headers: {
Authorization: `Bearer ${userId}`,
},
complete: function (result) {
// console.log('complete');
},
error: function (jqXHR, status, erreur) {
// console.log('error');
},
beforeSend: function (xhr, settings) {
console.log(`beforeSend beforeSend beforeSend beforeSend beforeSend beforeSend + ${userId}`);
xhr.withCredentials = true;
xhr.Authorization = `Bearer ${userId}`;
}
});
Hopefully this could help someone one day

Related

flask-cors is not parsing the data from ajax client

I am using flask for creating some endpoints for a blockchain project . I need to accept json data from ajax client . Since it is cros platform , i am using flask cors . But i cant seem to find a solution. It is not working
I have already tried doing
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, origin = '*')
Basically my client code is as follows .
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: true
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
And at my server i have an endpoint of
#app.route('/ratings/new', methods = ['POST','OPTIONS'])
def rating():
values = request.get_json()
if values == None:
return "No data received", 400
#ratings = values['rating']
index = blockchain.new_ratings(values)
response = {
'Message': f'New transaction will be added to the block {index}',
}
response = jsonify(response)
response.headers.add('Access-Control-Allow-Origin','*')
return response, 201
At the server side i am not receiving the required data and at the client side i am getting the following error .
Access to XMLHttpRequest at 'http://localhost:8080/ratings/new' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Please help me solve this problem . Thanks in advance.
Silly mistake , make the withCredentials: false
$.ajax({
url: 'http://localhost:8080/ratings/new',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: json1,
crossDomain: true,
xhrFields: {
withCredentials: false
},
processData: false,
beforeSend: function (xhr) {
//xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data, textStatus, jQxhr)
{
$('body').append(data);
console.log(data);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});

Lexik Bundle Symfony 3

I use LexikAuthentication Bundle. When I try to make the UI using ajax for login_check, I get back the token in localStorage but when I try to login to my UI, I get 401 not authorization.
This is my login_check:
function authenticate(e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:8000/login_check',
type: 'POST',
data: JSON.stringify({
'_username': $('#username').val(),
'_password': $('#password').val()
}),
dataType: 'json',
contentType: "application/json",
access_token: "",
crossDomain: true,
success: function (data) {
if (data != null && data != '') {
var token = "Bearer " + data.token;
console.log(token);
localStorage.setItem('token', data.token);
}
}
});
Anyone know how to fix this?
Okay i found the solution by my self.
The error was Here : localStorage.setItem('token', data.token);
It should be like this : localStorage.setItem("Bearer " ,data.token);

no display fail message from controller

I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

AngularJS - using data from a service in a directive

I have set up a service to collect JSONP data from a server. If I use console.log to output 'data.d.results' in the service, I get a simple array object with six items.
However, when I do the same thing within the directive I get a much more complex object returned - one containing $$state, error, success, proto at the top level.
Because this is a more complex object, I can't figure out how to refer to the actual data that I'm after.
Can anybody tell me where I'm going wrong when passing the data or what I need to do to reference the data in the directive? When I go down the tree in the developer tools I find the actual data here:
d > $$state > value > data > d > results > [0-5] > CardID
My code is below:
app.directive('dashboardcard', ['DashboardCardService', function(DashboardCardService){
return{
restrict: 'E',
link: function($scope, element, atttributes){
$scope.data = DashboardCardService;
},
template: 'Card Name: {{CardID}}'
};
}]);
app.factory('DashboardCardService', ['$http', function($http){
var request = {
method: 'GET',
url: '/api.svc/tbl_Card/',
dataType: 'jsonp',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true
};
return $http(request).success(function(data) {
return data.d.results;
});
}]);
Thank you
One way to make it work with your current code and minimum changes would be something like that
app.directive('dashboardcard', ['DashboardCardService', function(DashboardCardService){
return{
restrict: 'E',
link: function($scope, element, atttributes){
DashboardCardService.success(function(data){
$scope.data = data
});
},
template: 'Card Name: {{CardID}}'
};
}]);
app.factory('DashboardCardService', ['$http', function($http){
var request = {
method: 'GET',
url: '/api.svc/tbl_Card/',
dataType: 'jsonp',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true
};
return $http(request)
}]);
or
app.directive('dashboardcard', ['DashboardCardService', function(DashboardCardService){
return{
restrict: 'E',
link: function($scope, element, atttributes){
$scope.dashboardService = DashboardCardService;
},
template: 'Card Name: {{dashboardService.data.CardID}}'
};
}]);
app.factory('DashboardCardService', ['$http', function($http){
var service = {};
var request = {
method: 'GET',
url: '/api.svc/tbl_Card/',
dataType: 'jsonp',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true
};
$http(request).success(function(data) {
service.data = data.d.results;
});
return service
}]);
You can also check my plunk that demonstrates several ways to put data into directive from service
http://plnkr.co/edit/YOzP2VCPOXwh4qoQC73i?p=preview

Chrome extension transfer to manifest 2 - No ajax response

Hayush!
Been trying to transfer my Chrome extension to manifest 2. Everything is working except for one script which calls an ajax. I have a variable that contains a JSON content which needs to be transferred to the server.
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
For some reason the ajax part is not executed at all. No error message was triggered, nor in the server error log.
All of the inline scripts and scripts in general were included in the popup.js. So it's probably not the issue.
Any thoughts?
Thanks!
The following code works perfectly on previous manifest
function importbookmarks(){
$('#formadd').css('display','none');
$('#importing').css('display','block');
_gaq.push(['_trackEvent', 'chromextension','importbookmarks', username]);
chrome.bookmarks.getTree(function(bookmarks) {
sendlist(bookmarks);
});
}
function sendlist(list){
jsontext = JSON.stringify(list);
$.ajax({
url: amfurl + "user/listbookmarks/",
dataType: 'text json',
async: true,
type: 'POST',
// processData: false,
data: {'folders': jsontext},
success: function(data){
$('#importing').css('display','none');
$('#importdone').css('display','block');
console.log(data);
}
});
}
The problem wasn't with the function. The button execution wasn't calling it correctly.
Here is the code I used to get the function to work in manifest 2
document.addEventListener("DOMContentLoaded", function () {
document.getElementById("import-bookmarks").addEventListener("click", function () {
importbook();return;
});