How to set CORS header in cloudflare workers? - cloudflare

I'm using cloudflare workers to create a reverse proxy but I can't use it to embed on main domain cause it gives CORS error:
Access to image at 'https://example.workers.dev/96384873_p0.png' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
here's the code in workers
addEventListener("fetch", event => {
let url = new URL(event.request.url);
url.hostname = "i.pximg.net";
let request = new Request(url, event.request);
event.respondWith(
fetch(request, {
headers: {
'Referer': 'https://www.pixiv.net/',
'User-Agent': 'Cloudflare Workers'
}
})
);
});
How can I fix the CORS error?

You should read up on CORS to understand why you are receiving this error, then the fix should be straightforward (setting additional headers) - https://web.dev/cross-origin-resource-sharing/

Related

get CORS problem when ty to get a token in keycloak with vuejs and axios

I trying to access one keycloak with axios in my vuejs app, but I receive the cors error, can someone help me please? (If I make a post from POSTMAN to my keycloak works fine)
I using this code:
const params = new URLSearchParams();
params.append("grant_type", "password");
params.append("client_id", "notas-front");
params.append("username", usuario.value);
params.append("password", password.value);
console.log(params);
const config = {
// withCredentials: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
axios.defaults.headers.common["Access-Control-Allow-Origin"] =
"http://localhost:8080";
axios
.post(
"http://localhost:8082/auth/realms/lumera/protocol/openid-connect/token",
params,
config
)
.then((response) => {
console.log(response);
});
and get this error:
but when I look the request I can't find the error:
the OPTIONS returns 200
but the POST dont
Postman doesn't care about Same Origin Policy, browser do. That's why your request is working in Postman but not in the browser.
Access-Control-Allow-Origin is a response header, you can't set it on the client request. And as you can see from the OPTIONS response headers your server is returning: Access-Control-Allow-Origin: http://localhost:8080
In a development environment the best way to solve this is setting a proxy in your vue configuration. Otherwise you should configure the server to allow requests from localhost:8080
Configure Web Origins properly in the Keycloak notas-front client config.

APIGateway CORS enabled and Lambda proxy integration enabled but still running into CORS issues

I have the following CDK code for my API Gateway
this.restAPI = new RestApi(this, name, {
cloudWatchRole: true,
domainName: {
domainName: props.recordName,
certificate: props.cert,
endpointType: EndpointType.REGIONAL,
securityPolicy: SecurityPolicy.TLS_1_2
},
defaultCorsPreflightOptions: {
allowOrigins: Cors.ALL_ORIGINS,
allowMethods: ['OPTIONS', 'POST', 'GET', 'DELETE', 'PUT', 'PATCH'],
allowHeaders: Cors.DEFAULT_HEADERS,
maxAge: Duration.seconds(86400)
}
});
which results in this
But I'm still running into this error:
/#/actors:1 Access to fetch at 'https://web-api.alpha.myapp.com/api/v1/actors?page=1' from origin 'https://alpha.myapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
But if you look at my Access-Control-Allow-Origin it's set to '*'. So I'm not sure what I'm missing.
And just to validate I do have Lambda Proxy integration turned on
Apparently my lambda that returns the GET content actually has to include the relevant CORS headers. It's not enough to just turn on CORS support on API Gateway.

Vue.js - CORS error in local and production

I have got a file that's name is request.js,
import axios from 'axios'
const baseURL = 'https://SOME_URL.com/api/'
const config = {
baseURL,
timeout: 10000,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
}
}
const request = axios.create(config)
export default request
and I'm trying to send request in Vuex Actions;
import request from '../request'
const actions = {
postData(_, payload){
return request.post('a-request-url', payload)
}
}
Sending 2 requests and throws a CORS error when I run request. CORS error Access to XMLHttpRequest at 'https://crm.clinic/api/crm/login' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response
AND 2 requests like;
and the real problem, cors error continious when deploy my code as production. Can you help me?
If you read the second part in the error it says where the issue is.
Request header field access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response
As you can see you need to allow access in preflight response. A preflight request is something the browser does before sending your actual GET/POST/etc request. In the devtools' network tab you have 2 requests for the /login url. First one is a preflight using OPTIONS method.
To fix the issue you need to make sure your backend server returns 'Access-Control-Allow-Origin': 'http://localhost:8080' header in it's response for OPTIONS requests. Currently it is specifying only allowed methods and headers. You don't need to add those headers to your axios request.

No 'Access-Control-Allow-Origin' header is present on the requested resource with CORS module enabled

I am trying to get CORS working on my AWS Lambda server using Serverless. Right now I have two sub-domains (api.site.co and app.site.co).
In my app.js file on Express, I have installed CORS and enabled it like such:
app.use(
cors({
origin: 'https://app.site.co',
optionsSuccessStatus: 200,
}),
);
app.options('*', cors());
And then using the Axios module in React, I make this call:
axios
.post('/users/register', user)
.then(res => history.push('/login'))
.catch((err) => {
dispatch({
type: GET_ERRORS,
error: err.response.data,
});
});
Also, in my app.js file for the client app:
axios.defaults.baseURL = 'https://api.site.co';
When submitting any request, I receive this error:
Access to XMLHttpRequest at 'https://api.site.co/users/register' from origin 'https://app.site.co' 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.
So, far I have also tried changing my CORS configuration to:
app.use(cors());
app.options('*', cors());
But I am still getting the same error.
Any suggestions on how to address this?
Looks like there is a typo:
https://app.site.co/users/register => https://api.site.co/users/register
You're making a request to https://api.site.co but your configuration specifies https://app.site.co
This was a problem with the AWS Lambda Serverless setup. I needed to add
functions:
app:
handler: app.handler
events:
- http:
path: /
method: any
cors:
origin: 'https://app.site.co'
- http:
path: '{proxy+}'
method: any
cors:
origin: 'https://app.site.co'
So that it would allow CORS requests when proxying to the Express middleware.

Routing error in vue.js - Access to XMLHttpRequest at

i'm new in vue.js
i wrote an method for posting data and get page address (get and post) like this
updateCategory() {
this.$eventBus.$emit("loadingStatus", true);
this.$axios.get("http://rimonbd.com/tutorial/api/update-category", this.clickedCategory)
.then(res => {
this.$eventBus.$emit("loadingStatus", false);
this.showingAddModal = false;
if (res.data.error) {
this.$iziToast.error({
title: 'Error',
message: res.data.message,
});
} else {
this.$iziToast.success({
title:'Succes',
message:res.data.message,
});
and i got this error :'(
Access to XMLHttpRequest at 'http://rimonbd.com/tutorial/api/get-category' from origin 'http://localhost:8080' 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.
how should i fix that ?
The website you're trying to request data doesn't allow requests from different domains. You're on localhost:8080 requesting data from and external website.
You can try
Use local data to test your project
Deploy your project under the same domain of your data.
Read more about CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Try a hack, only for tests, don't put this in production https://cors-anywhere.herokuapp.com/
example:
this.$axios.get("https://cors-anywhere.herokuapp.com/http://rimonbd.com/tutorial/api/update-category", this.clickedCategory)