How to save an axios request as json object? - javascript

I am building a web applications with offline capabilities and i want to save the API requests as json in localStorage and make the request when connection is available, i am using axios to make the API requests, so lets say i have this request
$axios.post(`/users/`, {username: 'user', password: 'supersecretpassword'})
.then(response => {
console.log(response);
})
.catch(error => {
});
what i want to do is get this request as an object and use that object later to make the request. is this possible? how?
Thank You.

localStorage does not allow saving functions, but what you could do is save the request options object and use with a slightly different but documented Axios syntax:
var requestParams = {
method: 'post',
url: '/users',
data: {
username: 'user',
password: 'supersecret password'
}
}
axios(requestParams).then(....)
You can then decide to keep requestParams in localStorage and use it whenever you wish.

You have to create a function for this:
function getUsers(){
return $axios.post(`/users/`, {username: 'user', password: 'supersecretpassword'})
.then(response => {
console.log(response);
})
.catch(error => {
});
}

Related

When i trying to wirte data in firebase db take an exception

I have got an a react native app, i need to save data in db with user's token. How can i do it?
It's my auth firebase:
Also i need an a real time db to save here data and user's token:
I have a registration of user, and i know that i need here to make an a api into realtime db mthod PUT for url: https://[PROJECT ID]-default-rtdb.firebaseio.com/, but how can i do it i didn't know, pls help:
const hanldeRegister = () => {
if (password !== confirmPassword){
alert("The passwords are different!")
}
else{
setIsLoading(true)
axios({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/v1/accounts:signUp',
params: {
key: 'A',
},
data: {
email,
password,
},
}).then((res) => {
axios({
method: 'POST',
url: 'https://identitytoolkit.googleapis.com/v1/accounts:update',
params: {
key: 'A',
},
data: {
idToken: res.data.idToken,
displayName: name + ' ' + surname
}
}).then((r) => {
setUser({...r.data, idToken: res.data.idToken})
}).catch(e => {
console.log(e, 'updaate profile error');
alert(e.message);
})
.finally(() => {
setIsLoading(false);
})
console.log(res.data)
})
.catch((error) => console.log(error.response.request._response))
}
}
Rather than attempt to explain the process in great depth, because that would be reiterating the already existing docs.
Here is a link to the getting started docs regarding firestorage.
https://firebase.google.com/docs/storage/web/start
You should also checkout the starting docs, in regards to setting up firebase with web.
https://firebase.google.com/docs/web/setup
Thi will guide you through the process of setting up and intergrading firebase with your JavaScript application.

How to stub an incoming http request (response) with cypress

How can I stub a response of a HTTP request?
Let me explain it with my code I have now:
Cypress.Commands.add("FakeLoginWithMsal", (userId) => {
cy.intercept('**/oauth2/v2.0/token', (req) => {
req.reply({
token_type: "Bearer",
expires_in: 3795,
access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJS"
})
req.continue((res) => {
})
})
With this code I am trying to stub the response for the following request:
But it still gives the following error, where I can understand the stub did not work:
We attempted to make an http request to this URL but the request
failed without a response.
I've tried already different intercept methods of cypress but I couldn't get worked.
I even can't intercept the /token endpoint with the following:
cy.intercept({
method: 'POST',
url: 'https://login.microsoftonline.com/xx-xx-xx-xx-/oauth2/v2.0/token',
}).as('apiCheck')
Update:
#Fody Thankyou vey much (again) for you respond. Actually I am trying to stub all the MSAL endpoints. It is not a testscript, but a login command.
Here it is:
Cypress.Commands.add("FakeLoginWithMsal", (userId) => {
cy.intercept('GET', '**/authorize', { fixture: 'authorizeStub.json' })
cy.intercept('GET', '**/v2.0/.well-known/openid-configuration', { fixture: 'openidConfigurationStub.json' })
cy.request({
method: 'POST',
url: 'https://login.microsoftonline.com/xxxxx/oauth2/v2.0/token',
body: {
grant_type: "password",
client_id: "xxxxxxxxxxxxx",
client_secret: "xxxxxxxxxxx",
scope: "api://xxxxxxxxxxxxxx/Cp.Use",
username: "xxx#xxxx.com",
password: "xxxxx",
},
form: true,
}).then(response => {
cy.log(JSON.stringify(response))
cy.intercept('response', { fixture: 'tokenStub.json' })
})
These are 3 endpoints, namely:
GET: /authorize (stubbed with a fixture)
GET: /openid-configuration (stubbed with a fixture)
Post: /token --> This POST has a response and there inside is the accesstoken. This response I need to stub.
And I guess that this response is a "incoming HTTP request" (see attachments). This incoming http response is exactly what I want to stub in a fixture.
I'm not sure without seeing the whole test, but are you are issuing the POST to microsoftonline from within the test using cy.request()?
If so, you can't use cy.intercept() to catch it, only requests from the app will be caught.
But you can append a .then() to the cy.request() to wait for the response.
cy.request({
method: 'POST',
url: 'https://login.microsoftonline.com/.../oauth2/v2.0/token',
})
.then(response => {
// handle response
})
Also in this code req.reply() and req.continue() you are both stubbing (with reply) and continuing to the server (with continue), which are opposite actions. You would only want to do one or the other.
cy.intercept('**/oauth2/v2.0/token', (req) => {
req.reply({
token_type: "Bearer",
expires_in: 3795,
access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJS"
})
req.continue((res) => {
})
})

How to pass parameters to an external API via Firebase Functions

I have rerouted an external API call using Firebase Functions and everything seems to be working just fine (I have the paid plan) however, I am not sure how to pass parameters from the client side. The code on the server side looks like this:
const functions = require("firebase-functions");
const cors = require("cors")({ origin: true });
const { default: axios } = require("axios");
exports.news = functions.https.onRequest((request, response) => {
cors(request, response, () => {
var config = {
headers: {
"X-Api-Key": functions.config().news.key,
},
};
axios
.get(
"https://newsapi.org/v2/everything?q=usa&from=2021-08-27&to=2021-08-28&sortBy=popularity",
config
)
.then((res) => {
response.send(res.data);
})
.catch((error) => {
response.sendStatus(error);
});
});
});
What I will be passing from the client side is the from and to dates which currently are hard coded in the url. Just to make sure, am I doing it right to make an API call from the client side using the generated link from the Firebase Functions:
https://us-central1-<PROJECT-NAME>.cloudfunctions.net/news/?
Thanks in advance for all your replies.
You can pass those params as query parameters similar to the API call:
axios({
method: 'get',
url: 'the_cloud_function_url?from=the_date&to=another_date'
});
These query parameters can be access by request.query in the Cloud function.
Alternatively, you can make a POST request from Axios (client-side) and pass the data in body:
axios({
method: 'post',
url: 'the_cloud_function_url',
data: {
fromDate: '2021-08-27',
toDate: '2021-08-29'
}
});
This data can be read in cloud function using the request object:
exports.news = functions.https.onRequest((request, response) => {
const {fromDate, toDate} = request.body
console.log(fromDate, toDate)
// continue
})
Send data in body and handle the request.

Is there any way to create users with roles assigned in keycloak using node?

i was trying a code to upload all users to keycloak user list and it works well. i used an excel file to read then push each row into keycloak field but i was thinking to add roles to each user at the same time. when i try out this code it says role field does not exist in user and gives me error
this is my code
Read From Excel and store in an array
let path = 'http://localhost:8080/auth/admin/realms/msportal';
let _userTobeCreated = ReadFromExcel('./uploads/employees-roles.xlsx');
function ReadFromExcel(filename) {
let userTobeCreated = []
xlsxFile(filename).then((rows) => {
rows.forEach(row => {
let userObject = {
username: row[0],
lastName: row[1],
firstName: row[2],
email: row[3],
roles: row[4].split(',')
}
userTobeCreated.push(userObject);
});
})
return userTobeCreated;
}
create function
function CreateKCBulkUser(user) {
let urlCreateUser = `${path}/users`;
return axios({
method: 'post',
url: urlCreateUser,
data: JSON.stringify(user),
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${kc_accessToken}`
}
})
.then(function (response) {
console.log("User created!!");
_userlists = response.data;
})
.catch(function (error) {
console.log(error);
});
}
Calling Function
_usersToBeCreated.forEach((v)=>{
CreateKCBulkUser(v);
})
excel file
Role is not a part of user entity. First you must create role entity and then you need to create role-mapping. See API doc.
BTW: role is vague definition, because Keycloak has real roles/client roles + I would use keycloak-nodejs-admin-client instead of plain axios requests.

How to login user to spring-security app using Vue.js?

Hi it's my first post on stack overflow. I want to separate back-end from front-end and create REST API using my Spring Boot app. I use spring-security to login. It use something called JSESSION_ID but how to login and authorize users using Vue.js? I want to make form for login to my service and authorize request with JSESSION_ID.
It's my first app in Vue.js. I try to use code from tutorials and docs but it didn't solve my problem. I also have issues with CORS.
export default {
name: 'Login',
data(){
return{
username: '',
password: '',
error: false
}
},
updated(){
if (localStorage.token){
this.$router.replace(this.$route.query.redirect || '/')
}
},
methods:{
login(){
this.$http.post('http://localhost:8080/login', { username: this.username, password: this.password })
.then(request => this.loginSuccessful(request))
.catch(() => this.loginFailed())
},
loginSuccessful (req) {
if (!req.data.token) {
this.loginFailed();
return
}
this.error = false;
localStorage.token = req.data.token;
this.$router.replace(this.$route.query.redirect || '/')
},
loginFailed () {
this.error = 'Login failed!';
delete localStorage.token
}
}
}
I expect to login and authorize users from Vue.js using REST Spring-Boot API.
The problem is that you try to pass the object { username: this.username, password: this.password } as the data to the request, but you do not specify the Content-Type, which probably defaults to 'text/html' or 'application/json'. You could try to first convert that into form data and then pass it to the request, here is an example with AXIOS:
login() {
let formData = new FormData();
formData.set("username", this.username);
formData.set("password", this.password);
AXIOS.post('/login', formData, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.then((result) => {
this.loginSuccessful(result);
})
.catch((error) => {
this.loginFailed();
})
}
Perhaps it would also work without specifying the header, like AXIOS.post('/login', formData, null), haven't tried it.

Categories

Resources