export default new Vuex.Store and Mutations - javascript

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

Related

Using HTTP in NativeScript to send Post-data to a TYPO3-Webservice

I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});

Nuxt Auth Module - how to get a user by id/username

I'm attempting to integrate the 'Nuxt Auth Module' into my Nuxt App.
https://auth.nuxtjs.org/
I have configured my Proxy & Auth Modules and have setup the 'Local Strategy'.
https://auth.nuxtjs.org/schemes/local.html
My 'Login' endpoint works fine, and I set the 'propertyName' to 'access_token' as that is where the value for my token lives. I see 'Vuex' update my 'LoggedIn' status to true and I can also see the Token Response in the 'Network' tab of Chrome.
However I'm really struggling to understand how the 'User' endpoint works.
The example given:
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
logout: { url: '/api/auth/logout', method: 'post' },
user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
},
tokenRequired: true,
tokenType: 'bearer'
}
}
}
The above is pretty much identical to mine, how does the 'User' endpoint, know which user is logged in?
I am using a third-party system for my authentication as I'm integrating an application into the third-party system. Their 'User' endpoint for REST requires an 'ID' or 'UserName' to return details about a particular user.
My 'Login' response contains 'UserName' which I could use to call the subsequent User endpoint (If I knew how).
Does anyone know how the User endpoint works? Essentially I need to call something like this:
user: {
url: '/users/${userId}',
method: 'get',
propertyName: 'data'
}
Faced to this problem, too.
My solution:
Set user property of auth endpoint to false
auth: {
strategies: {
local: {
endpoints: {
// login api
login: {
url: '/api/v1/users/login',
method: 'post',
propertyName: 'token'
},
// logout api
logout: {
url: '/api/v1/users/logout',
method: 'post'
},
user: false // setting user fetch api to false
},
redirect: {
login: '/login',
logout: '/login',
callback: '/login',
home: '/'
},
}
}
},
After loginWith() You can use function setUniversal(key, value, isJson) to save fetched user and get it with function getUniversal(key)
async login(user) {
await this.$auth.loginWith('local', {
data: user
}).then(res => {
let user = res.data.data.user // getting user (yours can be different)
this.$auth.$storage.setUniversal('user', user, true) // setting user in Vuex, cookies and localstorage
user = this.$auth.$storage.getUniversal('user') // getting user (you can use it anywhere in your app)
console.log(user) // checking user
this.$router.push('/') // redirecting after login
}).catch(err => {
console.log(err.response)
})
}
That's all, you have your user in vuex, cookies, and localstorage you can get it in computed like this:
computed: {
user() {
return this.$auth.$storage.getUniversal('user');
}
}
P.S: to logout, use logout() function, and in the callback use this.$auth.$storage.removeUniversal('user') to remove it from everywhere

Difference between jquery ajax post and axios post

I am writing a new application using Vue.js As part of this I need to get an API token from a 3rd party. The ajax call below is working, and returns the expected response data object, however the axios call fails validation and returns an error message "Username and password cannot be empty". Any idea what I am doing wrong and why the two calls are being treated differently?
<script>
$(function(){
$.ajax(
{
type: "POST",
url: "https://testapi.XXXXXXXX.com/auth",
data: {
username:'TestUser',
password: 'TestPwd'
},
success: function(res){
console.log("from jquery",res);
}
}
)
})
</script>
<script>
var app = new Vue({
el:"#vueapp",
data:{
api_key: null
},
methods:{
getNewKey(){
axios({
method: 'POST',
url:'https://testapi.XXXXXXXX.com/auth'
,headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
,data:{
username:'TestUser',
password: 'TestPwd'
}
})
.then(response =>{
console.log("From Axios",response);
})
}
},
created(){
this.getNewKey();
}
})
</script>
From the axios documentation:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format
You need to JSON.stringify your object passed in data.
data: JSON.stringify({username:'TestUser', password: 'TestPwd'})

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

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;
}
})
}
}...

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