how to send response recaptcha token to backend using axios - javascript

I am using vue-recaptcha v3 on vue2 , and when I log response data of recaptcha request it is a fullfiled promise with a token and when I test it via postman and google verify api, it gets succeed.
but I don't know how to parse this promise and send the token to the Node backend using axios, my axios section doesn't work and I Get empty object {} at the backend side. anyone can help please?
methods: {
loginFunction: function() {
this.$recaptchaLoaded();
const token = this.$recaptcha('login');
console.log(token);
axios.post('http://192.168.27.167:3000/recaptcha',
{
token: token,
})
.then(response => {
}).catch(error => {
console.log(error)
})

it solved by a friend of mine as below with adding Async Await to the code and then at console log I get pure token to using for verification.
methods: {
loginFunction: async function() {
await this.$recaptchaLoaded();
// Execute reCAPTCHA with action "login".
const gresponse = await this.$recaptcha('login');
console.log(gresponse)

Related

How do I get access to response cookie received from server?

For my job I have to create a login on a page. I send my login data to the server using the fetch API and when it was successful, I will receive back a cookie.
However, I do see a cookie sent to me in my response, but I don't know how I can access it or set it on my front-end? Anyone knows how to do this?
Fetch function
const submitForm = async values => {
try {
const body = {
user: {
email: values.email,
password: values.password,
},
};
// don't mind the strange syntax here, it's a slightly modified fetch function wrapper
const response = await fetch.post('users/sign_in', {
body,
});
} catch (error) {
console.log('error', error);
}
};
Response I get from server, how do I actually get access to this cookie in javascript, or how can I immediately add it as a cookie in my browser?
Cookies of browser is still empty

Pass firebase access token to backend in axios interceptor

I need some help understanding how to pass in a firebase bearer/jwt token with my api requests to the backend.
I am using axios and using an interceptor to set up the bearer token similar to this
axios.interceptors.request.use(
config => {
const userData = store.getters['firebaseAuth/user']
if (userData && userData.accessToken) {
config.headers['Authorization'] = 'Bearer ' + userData.accessToken
}
In all the examples for firebase auth, I have seen that the way to get the jwt token is like so:
firebase
.auth()
.currentUser.getIdToken(/* forceRefresh */ true)
.then(idToken => {
Would it be good practice to run this in my interceptor to obtain the access token?..
Feels like an unnecessary extra api call to firebase servers for every request made to my backend server.
Also I have trouble understanding why I should even use this firebase method (getIdToken) when the token is available as a property from the user object. It has a strange name "za" which i think is deliberate from firebase, and nowhere mentions to use this to get the id/bearer/access token.
firebase.auth().onAuthStateChanged(user => {
if (user) {
//user.za id the id/bearer/access token
My initial thought was to just store user.za in localstorage then fetch it from local storage in the interceptor.
I'm not sure if it is the best way, but I ended up using the Firebase SDK methods in my interceptor directly. My understanding of the getIdToken API is that the promise returns a cached JWT, unless it is expired, in which case it will return a fresh one. I made the interceptor function async, and use await to synchronously request the token.
axios.interceptors.request.use(
async function (request) {
const user = currentUser();
if (user) {
try {
const token = await user.getIdToken(false); // Force refresh is false
request.headers["Authorization"] = "Bearer " + token;
} catch (error) {
console.log("Error obtaining auth token in interceptor, ", error);
}
}
return request;
},...

Store cookie connexion with Axios

I would like to have access to the information of an api with Axios, the problem is that Axios can't get the data. I have tested with Postman and I can access the data well.
I also noticed that Posteman stores a login cookie, I tried to reproduce with Axios but I can't.
I saw that axios.defaults.withCredentials = true had to be used, but it doesn't work, maybe I'm doing it wrong.
Here is my code:
getData() {
axios.defaults.withCredentials = true;
let url = "***"
axios
.get(url)
.then(response => {
this.name = response
}).catch((error) => {
this.name = error;
})
}
Thank you in advance!
Is this a NodeJS application? You may need to install something like tough-cookie. I was shown recently that https://github.com/salesforce/tough-cookie can be used to store cookies during your axiosJS requests. This could be helpful when a cookie is assigned after the request, such as during a 302 redirect.
The postman cookie is juste postman stuff if you didn't set it yourself, so it might not be useful for your axios request
Careful tho, axios returns the data like {"headers": stuff, "data": yourdata} where Postman just displays the data that's in the "data" key
So you might want to do
getData() {
let url = "***"
axios
.get(url)
.then(response => {
this.name = response.data
}).catch((error) => {
this.name = error;
})
}
otherwise, you can export your request Postman to code so you will see what Postman sends to the API (use the 'Code' button in Postman, under the 'Save' button)

How to fix/find 'Bad Request' and 'Denied' authentication errors in react

I am working on a user registration page in my group project and came across a bad request error when submitting the data. I created a button to get users so I can check the authentication and it gave me a 401. "HTTP401: DENIED - The requested resource requires user authentication. (Fetch)GET - http://localhost:49967/Users" When I login, I use the admin login that's in the database and I see a token in my developers options. How do I find this error? I am new to react and programming so if you can lend some advice or docs it would be appreciated.
So to test my api endpoint, I loaded Postman and attempted to GET/POST and everything worked. I am using a react front-end, SQL sever for the database and ASP.Net Core in Visual Studios c#.
For starters here is the const I am using to access the back end
const apiHelper = {
get(url, params){
return fetch(`${baseUrl}${url}`, {
headers: this.headers
})
.then(response => response.json())
.catch(error => {
console.log(error);
return Promise.resolve();
});
}
This is the onclick action
handleGetUsers = async() => {
const response = await apiHelper.get('Users')
if(response){
console.log(response)
}
}
Lastly my URL
http://localhost:49967/

Access SonarQube API with FetchAPI doesn't return any result

I am trying to access SonarQube API through Fetch but it doesn't seem to be responding with any results. It just resolves with an opaque token.
Let me share what I have done so far:
fetch("http://localhost:9000/api/issues/search?pageSize=500&componentKeys=bactch_analysis_key",{
mode:'no-cors'
}) // Call the fetch function passing the url of the API as a parameter
.then(
res => res.json()
)
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
I am setting the mode as no-cors as it was throwing ACAO errors.
The same URL works perfect when openend from chrome or inspected through Postman.
This is what I get when the promise resolves:
Below is the error that I get from the catch clause:
SyntaxError: Unexpected end of input
at fetch.then.res (index.html:51)

Categories