I am using angular js for my app.
Here , My Angular code as :
var app = angular.module('TaskManager', ['ngCookies']);
app.controller('LoginController', function($scope, $http, $location, $cookieStore) {
$scope.login = function(str) {
console.log(".......... login called......");
$http({
method: 'POST',
url: '../TaskManager/public/user/login',
data: $.param({
email: email.value,
password: password.value
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
var result = data.response;
console.log(result);
if (result == "success") {
//storing value at cookieStore
$cookieStore.put("loggedin", "true");
$cookieStore.put("loggedUserId", data.user_id);
$cookieStore.put("password", data.password);
$cookieStore.put("type", data.type);
$cookieStore.put("email", data.email);
location.href='Dashboard.html';
} else alert(data.message);
});
});
app.controller('DashboardController', function($scope, $http, $location, $cookieStore) {
$scope.users = [];
$http({
method: 'POST',
url: '../TaskManager/public/task/tasklist',
data: $.param({
logged_userid: userId,
password: password,
status: 'All',
user_id: useridToFetch
}),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status) {
console.log(data);
$scope.users = data.users;
});
//location.hash="";
console.log(window.location);
});
It works fine but when it redirects to the dashboard page after logged in, the location.hash is being assigned with the #/PAGE_NAME. it becomes location.hash=#/PAGE_NAMEwhich results the URL value repetition.
Like:
http://localhost:8085/NovaTaskManager/Dashboard.html#/Dashboard.html
I tried to clear hash at DashboardController, Which clears for a while but as soon as the page is refreshed the earlier URL appears again.
Don't know:
1. why location.hash is getting assigned by default ?
2. How it can be resolved ?
Any suggestion would be appreciated.
Related
I am calling a Google Cloud Function. I have a green arrow beside the function. I have enabled it to use HTTP. I have enabled it to work without authorization.
When I call it I get an error 403 and an object that says response type opaque. I have no idea what is wrong now ...
I have spent an entire day on this. And I'm so confused.
I'm calling it from both localhost:3000, and from an app I built on https://djit.su/
I have tried my best to figure out the CORS and everything else, but I am so stuck.
At this point I just want it to return "hey" to my local machine...
Here is my Google Cloud FN:
'use strict'
const functions = require('firebase-functions');
const cors = require('cors')({
origin: true,
});
exports.date = functions.https.onRequest((req, res) => {
console.log('Made it to here!');
if (req.method === 'PUT') {
return res.status(403).send('Forbidden!');
}
return cors(req, res, () => {
const stringVar = 'This is a string var';
console.log('Hi from inside cloud fn');
console.log('Sending:', { name: "Hi I'm Rick", stringVavr: stringVar });
const options = {
secure: false,
signed: false,
sameSite: None,
};
res.cookie('session', 'ABCE', options);
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.header('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
}
});
});
Here is my React code:
async function getNum() {
await fetch(
'https://us-central1-provable-fair-algo-rick.cloudfunctions.net/randomHash',
{ mode: 'no-cors' }
)
.then(function (response) {
// return response.text();
console.log(response);
console.log(json.response);
Promise.resolve(response);
console.log(Promise.resolve(response));
})
.then(function (text) {
console.log('Request successful', text);
})
.catch(function (error) {
console.log('Request failed', error);
});
Here is the console.log
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
The issue seems to be on your react code, as you are using { mode: 'no-cors' } however the Cloud Function is using CORS as it is in a different domain.
Here it explains that using no-cors can generate this opaque response:
no-cors is intended to make requests to other origins that do not have CORS headers and result in an opaque response, but as stated, this isn't possible in the window global scope at the moment.
A way to correct this would be to use: { mode: 'cors' } The code will be as the following:
function getNum() {
await fetch(
'https://us-central1-provable-fair-algo-rick.cloudfunctions.net/randomHash',
{ mode: 'cors' }
)
.then(function (response) {
// return response.text();
console.log(response);
console.log(json.response);
Promise.resolve(response);
console.log(Promise.resolve(response));
})
.then(function (text) {
console.log('Request successful', text);
})
.catch(function (error) {
console.log('Request failed', error);
});
I am currently trying to update a DynamoDB table with information that I add into a HTML form. Every time that I run my program and submit my information, I get this error:
POST https://quovje1gi8.execute-api.us-east-2.amazonaws.com/production/accounts 400 ()
I can run my Lambda function on AWS, and add data to my table just fine. I have checked again and again to make sure that my permissions are established correctly and they are. I just can't seem to figure this out.
My front-end:
<form>
<label for="username">Add Username:</label>
<textarea id="username"></textarea>
<button id='submitButton'>Submit</button>
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script type="text/javascript">
var API_URL = 'https://quovje1gi8.execute-api.us-east-2.amazonaws.com/production/accounts';
$(document).ready(function(){
$.ajax({
type:'GET',
url: API_URL,
success: function(data){
$('#accounts').html('');
data.Items.forEach(function(accountsItem){
$('#accounts').append('<p>' + accountsItem.username + '</p>');
})
}
});
});
$('#submitButton').on('click', function(){
$.ajax({
type:'POST',
url: API_URL,
data: JSON.stringify({"username": $('#username').val()}),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
Lambda function:
'use strict';
console.log('Starting Function');
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region:'us-east-2'});
exports.handler = function(e, ctx, callback) {
var params = {
Item: {
user_id: ,
date: Date.now(),
username: "",
password: "",
name: "",
location: "",
field: "",
company: ""
},
TableName: 'accounts'
};
docClient.put(params, function(err, data){
if(err){
callback(err, null);
}
else{
callback(null, data);
}
});
}
The following error prompts when my code executes.
It seems that bodyparameter could not be read.
missing required input JSON parameter requestType.
app.post('/compare', function (req, res, next) {
var options = {
host: 'hostname',
port: 80,
path: '/service',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': "Basic " + new Buffer(username + ":" + pass).toString("base64")
},
body: JSON.stringify({
requestType: 'createService'
})
};
var httpreq = http.request(options, function (response) {
response.on('data', function (chunk) {
console.log("body: " + chunk);
});
response.on('end', function() {
res.send('ok');
})
});
httpreq.end();
});
I checked node's http modules latest documentation for request method.
It's options parameter does not accepts any body attribute
There is a example as well which shows that you need to pass body in write method
const postData = JSON.stringify({
requestType: 'createService'
});
const options = var options = {
host: 'hostname',
port: 80,
path: '/service',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': "Basic " + new Buffer(username + ":" + pass).toString("base64")
}
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
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
I have a REST service that returns a JSON object. I am trying to make the authentication but it responses with empty data.
I did notice that the call is asychronous and when the user is pressing the login button it makes the call before getting the username and password. So I decided to use the $q constructor in order to fix it, but the problem consists, it still returns null data.
What am I doing wrong?
Thanks in advance.
factory
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', '$q', function($http, $q) {
return {
login: function(username, password) {
var deferred = $q.defer();
$http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: password})
.then (function(data, status, headers, config){
deferred.resolve(data);
}, function(data, status, headers, config) {
deferred.reject(data);
})
return deferred.promise;
}
}
}])
controller
.controller('MainCtrl', ['$scope', 'User', function($scope, User) {
$scope.username = "viewer";
$scope.password = "viewer";
$scope.login = function() {
User.login($scope.username ,$scope.password)
.then(function(response) {
console.log("success!");
$scope.status = response.status;
$scope.data = response.data;
$scope.username = response.username;
alert("Success!!! " + JSON.stringify({data: response.data}));
}, function (response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
console.log("Error!!!");
alert( "failure message: " + JSON.stringify({data: response.data}));
})
};
}])
*****EDIT*****
I did change the code a little bit. I think the problem was how the $http was written.
factory
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', function($http) {
return {
login: function(username, password) {
return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
}
}
}])
It did somehow worked but it returns loginCheck:false. It seems that it does not recognize the correct username and password.
response = Object {data: Object, status: 200, config: Object, statusText: "OK"}
log:
Object {data: Object, status: 200, config: Object, statusText: "OK"}config: Objectheaders: Objectmethod:
"POST"paramSerializer: (b)password: "viewer"transformRequest: Array[1]transformResponse: Array[1]url: "http://localhost:8080/CashInRestServices_war/rest/user/login"username: "viewer"__proto__: Objectdata: ObjectloginCheck: false__proto__:
Objectheaders: (c)arguments: (...)caller: (...)length: 1name: ""prototype: Objectconstructor: (c)__proto__: Object__proto__: ()<function scope>ClosureClosureGlobal: Windowstatus: 200statusText: "OK"__proto__: Object__defineGetter__: __defineGetter__()__defineSetter__: __defineSetter__()__lookupGetter__: __lookupGetter__()__lookupSetter__: __lookupSetter__()
constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get __proto__: get __proto__()set __proto__: set __proto__()
I figured it out. The login function was causing the problem $scope.login = function() so I used the $event object.
html
<div><button ng-click="login($event)" type="submit">Login</button></div>
factory
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', function($http) {
return {
login: function(username, password) {
// return $http({method:'post', url: 'http://localhost:8080/CashInRestServices_war/rest/user/login', username: username, password: password})
var data = {username: username,password: password};
console.log(JSON.stringify(data));
return $http({
method:'post',
url: 'http://localhost:8080/CashInRestServices_war/rest/user/login',
data: JSON.stringify(data),
headers: {'Content-Type': 'application/json'}
})
}
}
}])
controller
.controller('MainCtrl', ['$scope', 'User', function($scope, User) {
$scope.username = "viewer";
$scope.password = "viewer";
$scope.login = function(event) {
event.preventDefault();
User.login($scope.username ,$scope.password)
.then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
alert(JSON.stringify({data: response.data}));
}, function (response) {
$scope.data = response.data || "Request failed";
$scope.status = response.status;
alert( "failure message: " + JSON.stringify({data: response.data}));
})
};
}])
$http service is already returning a promise, so return it directly without using all the plumber :
login: function(username, password) {
return $http.post('http://localhost:8080/CashInRestServices_war/rest/user/login', {username: username, password: username});
}
}
Try like this, anyway if you can show us your console log.
angular.module('myApp', ['ngRoute'])
.factory('User', ['$http', function($http) {
return {
login: function(username, password) {
var myUrl = 'http://localhost:8080/CashInRestServices_war/rest/user/login';
var data = {
username: username,
password: password
};
return $http({
url: myUrl,
method: 'POST',
data: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
return response;
});
}
}
}])
Change your controller like this:
.controller('MainCtrl', ['$scope', 'User', function($scope, User) {
$scope.username = "viewer";
$scope.password = "viewer";
$scope.login = login;
////////////////////
function login() {
User.login($scope.username ,$scope.password)
.then(function(response) {
$scope.status = response.status;
$scope.data = response.data;
$scope.username = response.data.username; // I dont know if response.data.username exists but i am sure that response.username doesn't
}
};
}])