CORS policy: Request header field tron-pro-api-key is not allowed by Access-Control-Allow-Headers in preflight response - reactjs

I have a problem with trongrid. I dont know what to do. On trongrid i create API and put it in index.js
What config should i have on api settings on trongrid?
Console
Access to XMLHttpRequest at 'https://api.shasta.trongrid.io/wallet/getnodeinfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field tron-pro-api-key is not allowed by Access-Control-Allow-Headers in preflight response.
Here is my index.js
const TRONGRID_SHASTA_API = 'https://api.shasta.trongrid.io';
const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = new HttpProvider(TRONGRID_SHASTA_API);
const solidityNode = new HttpProvider(TRONGRID_SHASTA_API);
const eventServer = new HttpProvider(TRONGRID_SHASTA_API);
const privateKey = "c4f27f7b0523507**********************ecddfb21c891";
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey);
tronWeb.setHeader({'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
'TRON-PRO-API-KEY': '6ad9cb75-****-4f4c-a9cf-2156aa5e8453'});
async function triggercontract(){
console.log("trx:", tronWeb.trx);
console.log(tronWeb.transactionBuilder);
console.log(tronWeb.utils);
let instance = await tronWeb.contract().at("TNS*******tST9zAqXXssho5hgZ");
let res = await instance.f().call();
let res1 = await instance.g().call();
console.log("res", res);
console.log("res1", res1);
}
UPD 1:
I understand that: I have simple react-app, when i start it it up on localhost:3000 and it makes requests to api.shasta.trongrid.io/..... making post requests but api.shasta.trongrid.io dont give access to this localhost cause i dont have cors but how to set it cors correctly to work it project?
UPD 2:
Why my browser simply get info from this link, but react-app not? What should i do?

Related

Jeresy CORS filter working but React rest GET failing still with header ‘access-control-allow-origin’ is not allowed

I create a rest react front end to talk to a Jersey servlet on tomcat on the back end for RH 8.6. When react tried to do on REST GET or POST commands I got the "‘access-control-allow-origin’ is not allowed according to header" error. So I then added the CORS filter which was suppose to fix the origin problem, but the react client is still failing. I have tried different filters but there is no change. I assume the problem is in the react GET fetch but it looks ok with me and gets a header back when mode: 'no-cors' is set. In the debugger the CORSFilter class gets the GET, but it does not reach the resource class endpoint so its getting rejected.
Using postman I have verified the CORSFilter is inserting the values in the response as you can see here.
POST http://localhost:8080/rtc-servlet/mcd/location
Headers from postman tool:
Status Code: 200
access-control-allow-credentials: true
access-control-allow-headers: X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type
access-control-allow-methods: API, GET, POST, PUT, DELETE, OPTIONS, HEAD
access-control-allow-origin: *
access-control-max-age: 151200
connection: keep-alive
content-length: 701
content-type: application/json
date: Sat, 10 Dec 2022 02:52:19 GMT
keep-alive: timeout=20
servlet code:
#Provider
public class CORSFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
// *(allow from all servers) OR https://crunchify.com/
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
// As part of the response to a request, which HTTP headers can be used during the actual request.
responseContext.getHeaders().add("Access-Control-Allow-Headers",
"X-Requested-With, CSRF-Token, X-Requested-By, Authorization, Content-Type");
Also tried these options:
"Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
responseContext.getHeaders().add("Access-Control-Allow-Methods",
"API, GET, POST, PUT, DELETE, OPTIONS, HEAD");
// How long the results of a request can be cached in a result cache.
responseContext.getHeaders().add("Access-Control-Max-Age", "151200");
}
}
#GET // read in updated/original files
#Produces(MediaType.APPLICATION_JSON) // what format we send back
public JsonObject getLocationValues() {
System.out.println("Called location getLocationValues ");
return locationRepository.readConfigFile(false);
}
React Rest GET fetch:
const urll1 = "http://localhost:8080/rtc-servlet/mcd/location";
useEffect(() => {
const fetchPost = async () => {
await fetch(urll1, {
// mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
"Accept": "application/json",
"Access-Control-Allow-Origin": "*",
},
})
.then((response) => {
if (response.ok) {
response.json().then(data => {
console.log("response fetchPost :" + JSON.stringify(data));
setPosts1(data);
});
} else {
console.log("response was not ok");
}
})
.catch((err) => {
console.log(err.message);
});
};
fetchPost();
}, []);
The console error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: header ‘access-control-allow-origin’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rtc-servlet/mcd/location. (Reason: CORS request did not succeed). Status code: (null).
NetworkError when attempting to fetch resource.
So does anyone see that I am doing wrong?
After read the CORS not working posts in stackoverflow again I came across a commit about getting the origin from the header and then setting Access-Control-Allow-Origin to it vs. "*" and react on port localhost:3000 started to get responses back from the localhost:8080 servlet (origin is being set to "localhost:3000"). This was the forum string if you want to read up on it:
How to enable Cross domain requests on JAX-RS web services?.
So the change in the filter class is as follows:
String origin = requestContext.getHeaderString("origin");
if ((origin != null) && (!origin.isEmpty())) {
headers.add("Access-Control-Allow-Origin", origin);
} else {
// *(allow from all servers) OR https://crunchify.com/
headers.add("Access-Control-Allow-Origin", "*");
}
headers.add("Access-Control-Allow-Credentials", "true");
and in the js script "Access-Control-Allow-Origin": "*" was deleted:
await fetch(urll1, {
headers: {
'Content-Type': 'application/json',
"Accept": "application/json"
},
})
I am not sure if I now need the else since "*" didn't work for me, but I left it in. If its not needed or I am just doing something that sort of works because I am using firefox please let me know.

I Always Got Cors Error When Send DELETE request to gcs Resumable Singed Url

I've tried to use "resumable signed url" when uploading a file.
This is the CORS config on the bucket:
[{“maxAgeSeconds”: 3600, “method”: [“GET”, “PATCH”, “DELETE”, “OPTIONS”, “POST”, “PUT”], “origin”: [“*”], “responseHeader”: [“*”]}]
BE
const options: GetSignedUrlConfig = {
version: 'v4',
action: 'resumable',
expires: Date.now() + 60 * 60 * 1000, // 60 minutes
contentType: 'text/plain',
};
FE
const res1 = await axios.post(
signedUrl.url,
{},
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/plain',
'x-goog-resumable': 'start',
},
}
);
const res2 = await axios.put(res.headers.location, file);
Uploading the file works successfully.
The problem is when I sent a 'DELETE' request via the url while uploading. The below code is what I used.
Google Docs Link
await axios.delete(resumable_signed_url_session_uri, {
headers: {
'Content-Length': '0'
}
});
What I expected to happen is that the file is being stop uploaded. but I got a CORS error. To be more specific, in the Console panel of Chrome, I saw an error like this:
'xhr.js?78a4:193 Refused to set unsafe header "content-length"'.
After this error, I got a CORS error:
Access to XMLHttpRequest at 'https://storage.googleapis.com/%5Bbucket%5D/test/test.mp3? ... &upload_id=ADPycdvPhSounQyXYnfOeyiXu-reeZf2j2ghdrXzHcUkSNzoFmmTa3k8Mutis_hhXJjEiMbP6TtzSbjuXzXSClvHUrqdNUlvCJiy' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Where is it wrong? Any help would be appreciated.

Can't get response from axios POST request (React)

I'm trying to get the response header from this axios request:
const res = await axios.post(process.env.REACT_APP_URL_API + "/login", {
username: userRef.current.value,
password: passwordRef.current.value,
}).then(response => console.log(response.headers))
The status is 200 and I got 2 responses
"OPTIONS", which his, from what I have read, related to CORS policy
CHROME response OPTIONS
And POST response, with the headers I need (credential, JWT and all)
CHROME response POST
Here is my problem: in axios response i'm getting the OPTIONS headers wish are useless and I don't know how to access the "real" data in POST, how do I adress this?
Resolved
In the end it was a backend (Spring) CORS config problem, I had not configured proper headers visibility.
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
List<String> allowOrigins = Arrays.asList("*");
configuration.setAllowedOriginPatterns(allowOrigins);
configuration.setAllowedMethods(singletonList("*"));
configuration.setAllowedHeaders(singletonList("*"));
//Adding following line made the required headers visible in frontend
configuration.setExposedHeaders(List.of("Authorization", "Role", "Username"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

How to fix python flask cors issue using flask-cors library

I could really use some help. I can't figure out what I'm doing wrong. I keep getting
Edit : Frontend React application runs on localhost:3000, backend is running on localhost:5000
Access to XMLHttpRequest at 'http://localhost:5000/api/auth/login' 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.
def create_app(test_config=None):
logger = logging.getLogger(__name__)
logger.info("Flask App Starting")
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
CORS(app)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
logging.getLogger('flask_cors').level = logging.DEBUG
app.config.from_mapping(
SECRET_KEY="dev",
JWT_SECRET_KEY="super secret key",
JWT_ACCESS_TOKEN_EXPIRES=timedelta(hours=2),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile("config.py", silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
jwt = JWTManager(app)
"""
Adding blueprints
"""
from app.routes import tester
from app.routes import auth
from app.routes import api_routes
from app.routes import similar_routes
app.register_blueprint(tester.bp)
app.register_blueprint(auth.bp)
app.register_blueprint(api_routes.bp)
app.register_blueprint(similar_routes.bp)
#app.before_request
def check_login():
"""Before each request check if token exist."""
pass
logger.info("Checking if token is required")
if (not getattr(app.view_functions[flask.request.endpoint], "is_public", False)):
logger.info("Token required")
try:
result = verify_jwt_in_request(locations="headers")
logger.debug(f"Identity sent in is {get_jwt_identity()}")
except Exception as e:
logger.error("Error occured during checking token")
logger.error(e)
return jsonify(msg="Token Expired"),401
#app.errorhandler(Exception)
def all_exception_handler(error):
logger.error("Error caught" + str(error) )
return jsonify(msg="Oh no! A Server error occured. :,( "), 500
return app
if __name__ == "__main__":
loggingSetup()
app = create_app()
logger.info("App Created")
app.run(debug=True)
logger.info("App Running")
I'm making API calls from my react frontend, using axios
axios.defaults.baseURL = "http://localhost:5000/api"
function getHeaders(token){
return {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
"Authorization": "Bearer " + token,
'Access-Control-Allow-Origin': '*'
}
}
async function createCustomObject(token) {
let url = "/ontology/create-object";
let options = {
method: "POST",
url: url,
headers: getHeaders(token),
};
let response = await axios(options).then((response) => {
let data = response.data
}).catch((error) => {
handleError(error.response)
})
return response;
What am I missing?
You would set your origin to http://localhost:3000:
cors = CORS(app, resources={r"/api": {"origins": "http://localhost:3000"}})
'Access-Control-Allow-Origin': 'http://localhost:3000'
I resolved my issue using proxy after trying a couple of failed attempts using CORS solution.
I simply put "proxy": "http://127.0.0.1:5000" in my package.json and therefore, I can then use
fetch(`/test`)
.then((res) => res.json())
.then((data) => {
//do something
});
easily in my app without actually providing the full url to the backend (http://127.0.0.1:5000).

mistakes in Headers in fetch request

I have a fetch request that works in browsers exept IE 11. It gets them from cache. To solve this problem I want to add headers in request.
async getResource(details) {
const mainUrl = "http://www.boredapi.com/api/activity";
const myHeaders = new Headers();
myHeaders.set("Pragma", "no-cache");
myHeaders.set("Cache-Control", "no-cache");
const res = await fetch(`${mainUrl}${details}`, {
mode: "no-cors",
headers: myHeaders,
});
}
I add details according details that user choose(sum of money, number of paricipants) It may look like '?participants=2&minprice=0.1'
And send request
const details = await this.getResource(`?participants=2&minprice=0.1`);
And got a mistake
Unhandled Rejection (Error): Could not fetch ?participants=2&minprice=0.1, received 0
I could solve problem with IE by adding cache: "no-cache", and deleting headers.

Resources