Vue-Cookies .set function isn't setting a cookie - javascript

Vue-Cookies .set function doesn't seem to set the cookie in Chrome, Safari or Firefox. Below is the code I'm using, called whenever someone authenticates:
vm.$cookies.set('token', response.headers.authorization)
Where "response.headers.authorization" is a real variable fetched from response data.
I get no errors in the console and I am able to see the site's cookies using the .keys function.
Does anyone have any ideas? I've posted a bigger block below to give some context.
export default {
name: 'Home',
components: {},
methods: {
sso: function () {
var vm = this;
axios({
method: 'POST',
url: api + 'secure/use',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
data: {
username: vm.$refs.username.value,
password: vm.$refs.password.value
}
}).then(function (response) {
vm.response = response.data;
if (response.headers.authorization) {
console.log(vm.$cookies.keys()) //THIS WORKS.
vm.$cookies.set('token', response.headers.authorization) //THIS HAS NO EFFECT.
vm.$router.push('/')
} else {
vm.error = true;
}
})
}
}...

Related

Scope problem: moved function now doesn't find variable

I am working on a hybrid app (just for my own) with Framework7 and almost everything is working fine. I want to tidy up the code and move some repeating code into a function. But now I get the error
ReferenceError: Can't find variable: resolve
I am just learning JS and had the last couple days learned more about scope and context, but I can't figure out why I get this error. As I understand, as the resolve() callback function is defined in outer scope, I must be able to call it from my custom function?
When I put the app.request() where my getJson() function is, it works. However, the request still works from within getJson() and I can see the data logged, but the resolve function won't work as expected.
routes = [
{
path: '/person/abc/',
async: function (routeTo, routeFrom, resolve, reject) {
var router = this;
var app = router.app;
var jwt = store.get('jwt');
app.preloader.show();
getJson(
jwt,
{document:'person'},
'Test',
'-/-'
);
},
},
];
function getJson(jwt, data, title, note) {
app.request({
url: 'https://example.com/json/',
method: 'GET',
dataType: 'json',
crossDomain: true,
data: { data },
headers: { Authorization: 'Bearer ' + jwt },
success: function(data, textStatus){
if (data.status === 'ALLOW') {
console.log('Data received');
resolve(
{
componentUrl: './pages/person.html',
},
{
context: {
title: title, note: note, person: data.person,
}
}
);
} else {
app.dialog.alert('Error loading data');
}
app.preloader.hide();
return;
},
error: function(xhr, textStatus, errorThrown){
console.log('Error', xhr.response);
app.preloader.hide();
app.dialog.alert('Error on request');
return;
}
});
}

export default new Vuex.Store and Mutations

I have problem with using commit like is described here. Probably problem is in that I use export default new Vuex.Store instead export const store = new Vuex.Store. But when I change this I have problem from this topic.
Here is my JS file, where I use Vuex and I want to call commit:
actions: {
signUserIn(payload) {
payload.password;
var params = new URLSearchParams();
params.append("grant_type", "password");
params.append("username", "admin");
params.append("password", "adminPassword");
axios({
method: "post",
url: "http://localhost:8090/oauth/token",
auth: { username: "my-trusted-client", password: "secret" },
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
data: params
}).then(function(response) {
const user = {
login: payload.username
};
localStorage.setItem("access_token", response.data.access_token);
this.commit("setUser", user);
});
}
},
Curently when I run this and I try call signUserIn I have this error in console: TypeError: Cannot read property 'commmit' of undefined
I don't have idea what can I type in google in this case.
I believe you have mistyped. It should be commit and not commmit.
EDIT: Seeing the file, please try using arrow functions instead.
axios({
method: "post",
url: "http://localhost:8090/oauth/token",
auth: { username: "my-trusted-client", password: "secret" },
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
data: params
}).then(response => {
const user = {
login: payload.username
};
localStorage.setItem("access_token", response.data.access_token);
this.commit("setUser", user);
});
This is because you will lose the context of this without it. With arrow functions, this remains the this from the outer context. Also, not sure if you need this in this particular case, but try with or without it. ( I said this too many times )
Note the signature of your action method is incorrect. The Vuex docs show that the action method takes the Vuex context (which contains the commit method) as the first parameter and the payload second:
// signUserIn(payload) { // DON'T DO THIS
signUserIn(context, payload) {
With your current code, you'll notice that payload.username and payload.password are undefined.
demo of your action with the bug
Your action method should look like this:
actions: {
signUserIn(context, payload) {
axios.post().then(response => {
context.commit('foo', foo);
});
}
}
demo of fix

React axios data type issue

I have the following submit method:
submitForm(e) {
e.preventDefault();
var token = document.getElementsByTagName("meta")[0].getAttribute("content");
var form = document.querySelector('.form');
if(navigator.onLine && JSON.parse(localStorage.getItem('candidates'))) {
axios({
url: '/save-data',
method: 'POST',
contentType: 'application/json',
data: {
"candidates": localStorage.getItem('candidates')
},
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
}
}).then(function(response) {
console.log(response);
})
.catch(function(e){
console.log(e);
});
}
else {
var singleCandidate = serialize(form, { hash: true });
var fromStorage = localStorage.getItem("candidates");
if (fromStorage) {
var parsedFromStorage = JSON.parse(fromStorage)
parsedFromStorage.push(singleCandidate)
localStorage.setItem("candidates", JSON.stringify(parsedFromStorage));
}
else {
localStorage.setItem("candidates", JSON.stringify([singleCandidate]));
}
}
}
it loads data from local storage and submits it if there is data and connection at the same time.
However there is something that doesn't work with the following:
data: {
"candidates": localStorage.getItem('candidates')
},
if I do:
data: {
"candidates": [
{
"name": this.state.firstName,
"email": this.state.email,
"university": this.state.university,
"degree": this.state.degree
}
]
},
I get a positive response, form data gets submitted. However I have to submit this value (localStorage.getItem('candidates')) and when I do that I get the following:
Should "localStorage.getItem('candidates')" be changed to another format?

How to set headers in Ajax call?

I am developing multi-language website using Angularjs and a Web api as backend. I am trying to send RequestedPlatform and RequestedLanguage in the header whenever I make an API call.
Below is my Ajax request call.
$http.post(url,RegistrationData).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function (error) {
toastr.error('', 'Error Occured');
});
updated code
var RegistrationData = {
FirstName: $scope.user.Fname,
LastName: $scope.user.Lname,
Password: $scope.user.password,
Gender: "Male",
DateOfBirth: "2017-04-04",
Nationality: $scope.user.selectedGlobe,
Mobile_CountryCod: "91",
MobileNumber: $scope.user.mobilenumber,
EmailId: $scope.user.email,
Home_Location: $scope.user.homeLocation,
Home_City: $scope.user.homeCity,
Home_Neighbourhood: $scope.user.homeNeighbourhood,
Home_HouseNumber: $scope.user.housenumber,
Home_MainStreet: $scope.user.homemainstreet,
Home_SubStreet: $scope.user.homesubstreet,
Work_Location: $scope.user.worklocation,
Work_City: $scope.user.workcity,
Work_Neighbourhood: $scope.user.workNeighbourhood,
Work_HouseNumber: $scope.user.workhousenumber,
Work_MainStreet: $scope.user.workmainstreet,
Work_SubStreet: $scope.user.worksubstreet
};
var req = {
method: 'POST',
url: url,
data: { RegistrationData: RegistrationData },
headers: {
RequestedPlatform: "Web",
RequestedLanguage: "English"
}
}
$http(req).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function () {
toastr.error('', 'Error Occured');
});
May I get some help to set headers in Ajax. Any help would be appreciated.
you can send headers with headers property of $http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
and if you want headers for all the requests that can be fully configured by accessing the $httpProvider.defaults.headers configuration object,
Reference
There are few ways and I have posted one which I have been using it for a while. I hope you are looking for the below
$http.post('test', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
})

angular: passing data to $resource service

Hi there I write a service of $resource for connecting the api.
here is the code in service.js
.factory('selfApi2', function ($resource, localStorageService) {
var AB = {
data: function (apiURL, header, data, params) {
return $resource("http://localhost:4000/api" + apiURL, null, {
update: {
method: 'POST',
headers: header,
data: data,
params: params
}
});
}
};
return AB;
})
in my controller.js
var header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var myData = {
'phone': '12345678'
};
selfApi2.data('/tableName',header,{where:{"name":"kevin"}).update(myData, function(result){
console.log("update Kevin's phone succeed",result);
})
it works. But why the variable myData should put inside the update() part rather than the data() part?
In your case, the data() is a function which will just create a ReST resource which would expose rest apis get save query remove delete as default.
So in this data() call you are just creating the rest resources. Passing myData with this function would not make any sense. The data() call would return the Resource instance which will have your update api function which accepts the parameters.
And, passing your data at api construction time does not make sense.
Here is the complete reference
I think it's because "data" is a function that returns object of $resource.
Try the scenario below:
// service
.factory('api', function ($resource) {
var api = {};
api.issues = $resource("http://localhost:4000/api/issues");
api.users = $resource("http://localhost:4000/api/users", {}, {
update: {
method: 'PUT',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
},
});
return api;
})
// controller
api.users
.update({where:{name:'kevin'}})
.$promise.then(function(success) {
// DO SOMETHING
});
...
api.issues.query().$promise.then(
function(success) {
// DO SOMETHING
});

Categories