Implementing google-recaptcha v3 in react without a backend - reactjs

I'm a frontend developer trying to create a test case of adding google-recaptcha-v3 in my react app.
I'd appreciate response to how i can by-pass the cors error when I make a post request to verify the user's token.
//imports
...
const Recaptcha=()=>{
return(
<div>
<p>Recaptcha Test</p>
<button onClick={handleSubmit}>Send Test</button>
</div>
)
// handleSubmit function
const handleSubmit =()=>{
const getToken = async () => {
await executeRecaptcha('contactpage')
.then(res=>{
console.log(res);
return setToken(res);
});
}
getToken();
console.log(token);
const verifyToken = async () => {
console.log(token);
const article = {
secret: '*******',
response: token
}
let axiosConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
"Access-Control-Allow-Origin": "http://localhost:3000",
}
};
let url = 'https://www.google.com/recaptcha/api/siteverify';
await axios.post(url, article)
.then(res => console.log(res))
.catch(err => console.log(err));
}
verifyToken();
}
Then I get this error in my browser console:
Access to XMLHttpRequest at 'https://www.google.com/recaptcha/api/siteverify' from origin 'http://localhost:3000/' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Google is not allowing you to call 'https://www.google.com/recaptcha/api/siteverify' from a frontend because of their CORS policy. See Mozilla's CORS guide for more information about CORS. Calls can only be initiated from a backend and not from a browser.

Related

How to fetch customers in reactjs using shopify api

I am new to API. I want to fetch customers in reactjs using shopify customer api.
I'm using following code:
const apiUrl = `https://${process.env.GATSBY_SHOPIFY_API_KEY}:${process.env.GATSBY_SHOPIFY_PASSWORD}#${shopify-store}/admin/api/${version}/customers.json`;
useEffect(() => {
fetch(apiUrl , {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
mode: 'cors',
})
.then((response) => {
console.log('response:', response);
})
.catch((error) => {
console.error('Error:', error);
});
},[])
Above code is producing error:
Url with cedentials can not be used in FETCH
I also tried using AXIOS. Code is following:
const getData = async () => {
try {
const res = await axios.get(apiUrl);
console.log("res >>>", res)
} catch(error) {
console.log("error >>", error)
}
}
Above code is also producing error:
Access to XMLHttpRequest at 'apiUrl' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Please help me out with api!
Thanks in advance
I want to solve the issue as soon as possible. I have tried all the methods I could find on internet.

CORS issue in calling userInfo from google API in react

I am using #react-oauth/google with Implicit method of getting user info from google account.
This is the code I use
const handleGoogleLogin = useGoogleLogin({
onSuccess: async (tokenResponse) => {
console.log(tokenResponse);
const token = pathOr('', ['access_token'], tokenResponse)
const userInfo = await axios.get(
'https://www.googleapis.com/oauth2/v3/userinfo',
{ headers: { Authorization: `Bearer ${token}`, "Access-Control-Allow-Origin": window.location.origin } },
);
console.log("user",userInfo);
},
onError: errorResponse => console.log(errorResponse),
});
In the axios request, I get the following error:
Access to XMLHttpRequest at 'https://www.googleapis.com/oauth2/v3/userinfo' from origin 'https://mywebsite:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Can anyone help fix this cors issue? Thanks!
I used XMLHttpRequest and it's working without any cors error.
const userInfo = await new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', `https://www.googleapis.com/oauth2/v3/userinfo`);
xhr.setRequestHeader('Authorization', `Bearer ${token}`)
xhr.onload = function () {
if (this.status >= 200 && this.status < 300)
resolve(JSON.parse(this.responseText));
else resolve({ err: '404' });
};
xhr.send();
});

How to enable CORS between http://localhost:3000/ and TMDB api in ReactJS?

I'm facing error where I can't get the data from TMDB API.
Access to XMLHttpRequest at 'https://api.themoviedb.org/3' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
axios.js setup
import axios from "axios";
const instance = axios.create({
baseURL: "https://api.themoviedb.org/3",
})
export default instance;
request.js setup:
const API_KEY = "xxx";
const request = {
fetchTrending: `/trending/all/week?api_key=${API_KEY}&language=en-US`,
fetchNetflixOriginal: `/discover/tv?api_key=${API_KEY}&with_networks=213`,
}
export default request;
App.js
useEffect(() => {
//if [], run once when row load, and dont run again
console.log("rrrrsd >>> ", typeof(fetchUrl))
async function fetchData(){
const response = await axios.get(fetchUrl, {
headers:{
'Access-Control-Allow-Origin': '*',
}
}).then(function (response){
console.log('response >>>>', response.data)
}).catch(function (error){
if(error.response){
console.log('response error >>>', error.response.headers)
}
else if(error.request){
console.log('error request >>>', error.request)
}
else{
console.log('message error >>>', error.message)
}
})
}
fetchData()
},[fetchUrl])
Please help me to enable CORS between TMDB API and ReactJS localHost
use a google chrome extension like (CORS Domain) or (Allow CORS )
I face the same problem yesterday and the extension fix it

ReactJS aws blocked by CORS preflight policy

I've been trying to make a simple post request api so that my reactJS frontend can make posts, and have them populate in a table in DynamoDB. I've created the a dynamoDB table, given a lambda function permission to make requests to this table, and an API gateway to use a url to make the rest api requests. I originally did not have the intergration request in API gateway set to lambda proxy, but from the advice of aws support, I've enabled it.
This is the code I'm using in my lambda function (with the api gateway (REST API) as the trigger):
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: "us-east-1"});
exports.handler = (event, context, callback) => {
console.log("Processing...");
const {name} = JSON.parse(event.body);
const params = {
TableName: "serverlessAppTest",
Item: {
date: Date.now(),
name: name,
},
};
let responseBody = {
name: name,
}
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify(responseBody)
};
docClient.put(params, function(err, data) {
if(err){
callback(err, null);
} else {
callback(null, data);
}
})
console.log("response: " +JSON.stringify(response))
return response;
};
When I try to reach the post api with the following body in the test area in lambda:
{
"body": "{\"name\": \"Value from Lambda\"}"
}
I got a 200 OK, and the data is populated in the dynamoDB table. It also works correctly in postman, a 200 OK and data uploaded.
When I try in my reactjs code, I get the following response:
Access to XMLHttpRequest at 'https://{apivalhere}.execute-api.us-east-1.amazonaws.com/default/serverlessAPICalls' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here's my reactjs function to make the call with a button push.
import React from "react";
import axios from "axios";
function FormHook() {
const apiURL =
"https://{apivalhere}.execute-api.us-east-1.amazonaws.com/default/serverlessAPICalls";
const submitHandler = (e) => {
e.preventDefault();
console.log("did it");
const headerData = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers":
"Origin, Content-Type, X-Auth-Token",
"Access-Control-Allow-Methods":
"GET, POST, PATCH, PUT, DELETE, OPTIONS",
};
axios
.post(
apiURL,
{
name: "Hello from reactjs!",
message: "this is the message field.",
},
{
headers: headerData,
}
)
.then((res) => {
console.log(res);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
<form onSubmit={submitHandler}>
<button type="submit">Send</button>
</form>
</div>
);
}
export default FormHook;
I've gone through about a dozen or more docs on stackoverflow and aws support trying to resolve this issue, and I keep getting blocked with this cors issue. I've tried specifically stating "application/json" in my headers, along with specifically allowing 'localhost:3000', then tried '*' in the Control Allow Origin for both the lambda node.js code, and reactjs post method. I'm at a complete loss at what I could do to fix this and could use some help. I'm relatively new with making my own functions to handle api requests, so any guidance or suggestions would be much appreciated.
edit:
I received the same CORS error with the following as well.
import React from "react";
import axios from "axios";
function FormHook() {
const apiURL =
"https://{apivalhere}.execute-api.us-east-1.amazonaws.com/default/serverlessAPICalls";
const submitHandler = (e) => {
e.preventDefault();
console.log("did it");
axios
.post(
apiURL,
{
name: "Hello from reactjs!",
message: "this is the message field.",
},
)
.then((res) => {
console.log(res);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
<form onSubmit={submitHandler}>
<button type="submit">Send</button>
</form>
</div>
);
}
export default FormHook;
For my setup in particular, the issue was in my api gateway configuration and process in lambda. I was not handling the OPTIONS request, which was causing the bad gateway (502 error). To fix this, in the api gateway I'd set an OPTIONS methods integration request type to MOCK. This causes the api gateway to just chuck out whatever OPTIONS request it gets, and allows the following post request to come through.
This is definitely not best practice and will be updated to handle the OPTIONS request more gracefully, but it's working now.
This great article explains the solution: AWS CORS Policy with React
You have to go through to every detail, I also read it several times to realise how to set the headers for every request right.

CORS error: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response

While loging out, this error occur.
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/auth/logout/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authentication is not allowed by Access-Control-Allow-Headers in preflight response.
I'm calling logout function of auth.js in as onClick. I don't know why I get logout when I refresh my page.
reducer.js
case LOGOUT_SUCCESS:
localStorage.removeItem("token");
return {
...state,
isAuthenticated: null,
isLoading: false,
user: null,
isFreelancer: false
};
logout function of action/auth.js
export const logout = () => (dispatch, getState) => {
const token = getState().auth.token;
const config = {
headers: {
"Content-Type": "application/json"
}
};
if (token) {
config.headers["Authentication"] = `Token ${token}`;
}
axios
.post("http://127.0.0.1:8000/api/auth/logout/", null, config)
.then(res => {
dispatch({ type: LOGOUT_SUCCESS });
})
.catch(err => {
console.log(err.message);
});
};
I expect to log out immediately but I get logged out while I refresh my page everytime.
If you are using Create-React-App, you can simply do this in your package.json file:
"proxy": "http://127.0.0.1:8000",
It will be proxy request and browser will not block response.

Resources