window.location.href doesn't work when using vue.js? - angularjs

When I use angular.js, I use $.ajax in methods, then window.location.href when it succeeds. It works.
But when I use vue.js, it doesn't work until I add window.event.returnValue = false; after it.
I think it has nothing to do with angular.js or vue.js, because I use $.ajax, not $http or others. But why doesn't it work when I use vue.js?
$.ajax({
url: 'xxx',
type: 'post',
dataType: 'json',
async : false,
data: {
'xxx' : xxx
},
success: function (response) {
if (response.status == 'success') {
window.location.href = 'xxx';
// window.event.returnValue = false;
}
},
error: function () {
xxx
}
});

Please try this. It work perfectly for me.
created() {
this.vm = #Json.Serialize(Model)
this.ppp = window.location;
this.path = this.ppp.pathname;
this.lastid = this.path.lastIndexOf("/");
this.id = this.path.charAt((this.lastid + 1));
this.url = this.ppp.origin + '/Controller/Action/' + this.id;
console.log(this.url)
axios.get(this.url)
.then(response => { this.summary = response.data });
},
data:
{
vm: [],
summary:[],
ppp:'',
id:0,
url:'',
}
Hope this help

Related

Angular $http.post to retrieve JWT

I am attempting to make my code more reusable, but have come across a problem when making $http calls, if I use my normal way:
vm.loginUser = function () {
var userData = {
username: vm.userName,
password: vm.userPassword,
grant_type: "password",
client_id: "E0..."
};
console.log('userData: ', userData);
var config = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d)) str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
};
console.log('config: ', config);
$http.post('https://a.n.org.uk/token', userData, config)
.then(function (response) {
console.log('Button clicked: ', response);
}, function (response) {
console.log(response.data.error_description);
}, function (response) {
console.log(response.data);
});
This works fine and doesn't give me any problems. I have made a factory that is basically the same but doesn't seem to work with giving me OPTIONS error in the console and preflight check... No 'Access-Control-Allow-Origin' header'I wondered if this is a simple fix, I am using Web API.
factory("homeResource", function ($http, $q) {
return {
getUser: getUser
};
function getUser(userData) {
var request = $http({
method: "post",
url: "https://a.n.org.uk/token",
data: userData,
config: {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d)) str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
}
});
return (request.then(handleSuccess, handleError));
}
function handleSuccess(response) {
return ( response.data );
}
In my Ctrl page I pass in my homeResource and call it like so homeResource.getUser(userData).then(function (res) {console.log(res);}); and get the errors mentioned. Is there a way to make this work?
try the following factory method
app.factory('homeResource', function($http) {
return {
getUser: function(userData) {
var config = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d))
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
};
return $http.post('https://a.n.org.uk/token', userData, config);
}
}
});
and use it in your controller like this.
app.controller('AppCtrl',function($scope, homeResource){
vm.loginUser = function () {
var userData = {
username: vm.userName,
password: vm.userPassword,
grant_type: "password",
client_id: "E0..."
};
homeResource.getUser(userData).success(function(res){
console.log("response is",res);
})
.error(function(err) {
console.log("err is",err);
});
}
})
Your error related to cross-origin request - in other words you send request to another domain or specific route miss Access-Control-Allow-Origin server header.
Check ports, http/https and domain. Seems it's not related to your refactor.

Send by post with restangular

I'm trying to send by post a json with restangular but this don't return me anything.
Code:
$scope.userPost = {
title: 'foo',
body: 'bar',
userId: 1
}
$scope.registerUser=function(){
$scope.people = Restangular.all('post').post($scope.userPost);
console.log($scope.people);
}
It return me this:
{ "restangularCollection": false, "$object": {} }
http://jsonplaceholder.typicode.com/post 404 (Not Found)
Usually I use this with ajax and it return me a json:
$.ajax('http://jsonplaceholder.typicode.com/posts', {
method: 'POST',
data: {
title: 'foo',
body: 'bar',
userId: 1
}
}).then(function(data) {
console.log(data);
});
Any ideas ?
Restangular works with promises, so, you should be doing something like:
$scope.registerUser = function () {
Restangular.all('post').post($scope.userPost).then((data) => {
$scope.people = data;
console.log($scope.people);
});
}
Or you can take advantage of its enhanced promises and do something like:
$scope.registerUser = function () {
$scope.people = Restangular.all('post').post($scope.userPost).$object;
}
In Angular 4+
constructor(private restangular: Restangular){}
// latter in your method
const baseUsers = this.restangular.all('post');
baseUsers.post({'title':'foo','body': 'bar','userId': '1'})
.subscribe(data => { console.log(data); });

Nodejs post request

I am trying to login to a website with the following request:
var request = require('request');
var options = {
method: 'POST',
url: 'https://server/EnterpriseController',
params: {a: 1},
form: "actionType=authenticateUser&reqObj=[null,username,password,null,1]",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
withCredentials: true,
rejectUnauthorized: false
};
request(options,
function (error, response, body, data) {
if (request.method === 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var post = qs.parse(body);
});
}
console.log(body);
}
);
I am always getting an error. I think the form is wrong but I have the same login on an angularjs site without any error. I don't understand why the login works on angularjs site but not in nodejs.
)]}',
{"login_err": true, "resp": [null,null,null,1]
}
I missed the cookie:/ And the Formdata should be an Object.

Post request is not working in angularjs - Resource services

I'm trying to send the post request to server with post data
it's sent the request to the server, but not in right format
request url like /rest/api/modifyuser/?currentPassword=admin&newPassword=admin
it's like GET request - (may be this is problem)
I'm new to angularjs . please share idea to solve this problem
Here is my code
In controller
var currentPass = "admin";
var newPass = "admin";
var confirmPass = "admin";
var authToken = "abcdef";
User.changePassword(currentPass, newPass, confirmPass, authToken, function(response) {
angular.forEach(response, function (item) {
alert("resp"+ item);
});
});
In services
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass, newPass, confirmPass, authtoken, callback) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'query': {
method: 'POST',
params: {
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
},
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
},
isArray: false
}
});
Resq.query(callback);
}
};
});
Thanks in advance
I dont want to say you are doing it all wrong.. but you are def. abusing things. The default way to POST something with ng-resource is to use save. Second, the default way to send data is to instantiate a $resource factory with the data you want. See _resource below. We pass the data we want, and it will automagically convert it and if its a POST send it in the body, or in the case of a GET it will turn into query parameters.
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass,
newPass,
confirmPass,
authtoken,
callback
) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'save': {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
}
}
});
var _resource = new Resq({
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
});
_resource.$save(callback);
}
};
});

Dynamic Resource Headers

I would like to have service providing a resource as in the following code:
angular.module('myApp.userService', ['ngResource'])
.factory('UserService', function ($resource)
{
var user = $resource('/api/user', {},
{
connect: { method: 'POST', params: {}, isArray:false }
});
return user;
}
Then when using the connect action, I would like to dynamically pass a HTTP header, meaning that it may change for each call. Here is an example, in the controller, please see the comment in the code :
$scope.user = UserService;
$scope.connect = function ( user )
{
var hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);
// I would like this header to be computed
// and used by the user resource
// each time I call this function
$scope.user.headers = [{Authorization: hash}];
$scope.user.connect( {},
function()
{
// successful login
$location.path('/connected');
}
,function()
{
console.log('There was an error, please try again');
});
}
Do you know a way to do that, either directly or via a trick?
Final thoughts
Accepted answer does not fully answer the question as the headers are not totally dynamic because the factory returns actually a factory (!) which is not the case in my code.
As $resource is a factory, there is no way to make it dynamic.
I finally destroy the resource object each time the user connects. This way, I have the resource with a header computed when the user connects.
The solution provided by #Stewie is useful for that, so I keep it as accepted.
Here is how I did the connect, which can be used multiple times as the resource is destroyed/recreated when (re)connecting:
this.connect = function (user)
{
self.hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);
console.log("CONNECT login:" + user.login + " - pwd:" + user.password + " - hash:" + self.hash);
if (self.userResource)
{
delete self.userResource;
}
self.userResource = $resource('/api/user/login', {}, {
connect: {
method: 'POST',
params: {},
isArray: false,
headers: { Authorization: self.hash }
}
});
var deferred = $q.defer();
self.userResource.connect(user,
function (data)
{
//console.log('--------- user logged in ----- ' + JSON.stringify(data));
// successful login
if (!!self.user)
{
angular.copy(data, self.user);
}
else
{
self.user = data;
}
self.setConnected();
storage.set('user', self);
deferred.resolve(self);
},
function (error)
{
self.user = {};
self.isLogged = false;
storage.set('user', self);
deferred.reject(error);
}
);
return deferred.promise;
};
Starting from angularjs v1.1.1 and ngResource v.1.1.1 this is possible to accomplish using the headers property of the $resource action object.
You may wrap your resource in a function which accepts custom headers as a parameter and returns a $resource object with your custom headers set at the appropriate action definitions:
PLUNKER
var app = angular.module('plunker', ['ngResource']);
app.controller('AppController',
[
'$scope',
'UserService',
function($scope, UserService) {
$scope.user = {login: 'doe#example.com', password: '123'};
$scope.connect = function() {
// dropping out base64 encoding here, for simplicity
var hash = 'Basic ' + $scope.user.login + ':' + $scope.user.password;
$scope.user.headers = [{Authorization: hash}];
UserService({Authorization: hash}).connect(
function () {
$location.url('/connected');
},
function () {
console.log('There was an error, please try again');
}
);
};
}
]
);
app.factory('UserService', function ($resource) {
return function(customHeaders){
return $resource('/api/user', {}, {
connect: {
method: 'POST',
params: {},
isArray: false,
headers: customHeaders || {}
}
});
};
});
I set my Services up a little differently.
angular.module('MyApp').factory('UserService',function($resource, localStorageService) {
var userResource = function(headers) {
return $resource("api/user", {},
{
get: {
method: 'GET',
headers: headers
},
create: {
method: 'POST',
headers: headers
}
}
);
};
return {
api: userResource,
get: function(userid){
var service = this;
return service.api({"token": "SomeToken"}).get({userid: userid}, function (data){
return data;
});
},
create: function(user){
var service = this;
return service.api({"token": localStorageService.get("token")}).create({user: user}, function (data){
return data;
});
}
};
});

Resources