Why doesn't the CORS problem occur on the backend server? - api

I am studying on a toy project using Vue. During development, I made api requests using axios from the front-end and faced a CORS problem. I would really appreciate it if you could give me some information.
Access to XMLHttpRequest at '...' 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.
I know CORS issues are caused by security issues when the requested domain and the responding domain are different. Is that so?
Anyway, I saw the information to enter "Access-Control-Allow-Origin": "*" in the request header, but it didn't work.
So I searched for more information. As a result, I created an express server and configured the proxy for the vue project as shown below.
//vue.config.js
module.exports = {
outputDir:"backend/public",
assetsDir:"assets",
configureWebpack: {
devtool: 'source-map'
},
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
And I just applied the basic example code provided by the api site to the default express environment.
The only thing that changed
Not requested from front-end. (A request was made at back-end (express).)
I used the request module, not axios.
Why doesn't a CORS error occur when I make an api request on back-end (express)?

According to MDN, CORS is a mechanism to add security to requests and data transfers between cross-origin browsers and servers, so it won't affect by back-end and proxy servers.
Modern browsers use CORS in APIs such as XMLHttpRequest or Fetch to
mitigate the risks of cross-origin HTTP requests.

Related

Vue.js CORS Problem in Kubernetes Cluster

I have a server with Fast API (Python) from which I get data over a REST API from my client (Vue.js on ngnix). Server and client are deployed in a Kubernetes cluster in one container each on a single Pod. I deploy the containers via dockerfiles.
When I send a GET request I get CORS problems. But locally (not on a Kubernetes Cluster) everything works. Error : Cross-source (cross-origin) request blocked: The same-source rule prohibits reading the external resource at http://localhost:5000/. (Reason: CORS request failed). Status code: (null).
In the following some code passages in which I suspect the problem.
FastAPI CORS Config:
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Vue.config.js:
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
// devServer: {
// proxy: '???' maybe need something here ?
// }
})
Maybe someone has an idea what the problem is or a tip what to try. So far I have unfortunately found no solution on the internet.
Thanks for your help <3
On server side I have already allowed everything as origin (*). I also tried different configurations on Vue.js, but I don't know anything about it and couldn't find a solution on the internet.

api request has been blocked by CORS policy

In my next.js project I'm trying to send a POST request using axios:
axios.defaults.baseURL = "https://{my-server-url}/api";
useEffect(() => {
axios({
method: "POST",
url: "/build_pages",
data: {
page_id: 3,
},
}).then((res) => {
console.log(res.data);
});
}, []);
I'm getting the following CORS error:
My server is [laravel] php and is deployed on cpanel, but before I deployed my backend to cpanel (i.e. when I was working on localhost) I did not get this error.
How do I turn off this error (note that I don't want to download any web browser extension to fix the CORS error)
I came across this link but it does not say where (which file) to add it to so I'm stuck
Edit: I tried the middleware solution provided in this answer: https://stackoverflow.com/a/69151121/12009071 but also it didn't work, howerver the error changed to:
Access to XMLHttpRequest at 'https://{my-server-url}/api/check_admin_login' from origin 'https://{my-server-url}.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
This is an API-side error. You have to allow cross origin requests on the API server. Based on your question, I assume your API is NOT the Next.js project.
Therefore, you should check the settings of your server. The next.js POST call is not the issue.

Manage CORS between Google App Engine & Google Cloud Function

I'm trying to set up a new instance of a simple App Engine which communicate with a backend-function hosted on Google Cloud Function. The App Engine is protected with IAP, and the Google Cloud Function is private only. The GAE use Angular Framework and GCF use Node 14 with Express
.
I can't access to my GCF from the App Engine because the requests are blocked by CORS.
Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I tried the popular solutions on the web :
Use the cors librairie on the GCF. So I had on my GCF
var cors = require('cors')
app.use(cors(cors({ credentials: true, origin: true })))
And I also add this line for every request
res.set('Access-Control-Allow-Origin', '*')
Add the http-header on my app.yaml
handlers:
- url: /(.*\.[A-Za-z0-9]{1,4})$
static_files: dist/\1
upload: dist/(.*\.[A-Za-z0-9]{1,4})$
http_headers:
Access-Control-Allow-Origin: "*"
- url: /(.*)$
static_files: dist/index.html
upload: dist/index.html
http_headers:
Access-Control-Allow-Origin: "*"
But I still get the same error message.
EDIT : so the first problem was due to an authentication issue, that why the error have the same response. So I decided to deploy the 2 apps on App Engine to simplify communication between the 2 services.
You can now have full access to the HTTP Request/Responses by setting
the appropriate CORS headers as per this documentation.
Just so you know the reason for the error you are facing, it is
because when your web browser is calling a service that is in a
different/cross domain, it doesn’t make a HTTP request right away, it
rather starts with making an OPTIONS request( a preflight request)
and compares the value of Access-Control-Allow-Origin header in the
result with the current domain i.e. it checks for this (req.method
=== 'OPTIONS') in the headers and if the header value matches the host, the actual call is made, otherwise the action is stopped and
the error as the one above is thrown.
To have a thorough understanding of the above concept, have a look at
this stackoverflow answer and read this article for more insights.

browser extension - CORS proxy error using axios [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Closed 2 years ago.
I'm using GimmeProxy api to get a proxy that I want to use in my vue chrome extension. Unfortunately I get this error:
Access to XMLHttpRequest at 'https://gimmeproxy.com/api/getProxy?get=true&supportsHttps=true&anonimityLevel=1&protocol=http' from origin 'chrome-extension://eamofepokjbdhndoegnmcnmgjhefhhlh' 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.
This is the code I have in my vuex action:
fetchProxyData({ commit }) {
axios({
method: 'get',
baseURL: 'https://gimmeproxy.com/api/getProxy',
params: {
get: true,
supportsHttps: true,
anonimityLevel: 1,
protocol: 'http'
},
headers: {
'Access-Control-Allow-Origin': '*'
}
}).then( (response) => {
console.log(response)
})
Is there a way to fix this?
In your code example, you are attempting to send the CORS headers from the client to the server.
It needs to be the other way around.
The client needs to respond to your request with the 'Access-Control-Allow-Origin': '*' header for this to work.
Can your check, using Chrome Dev tools network tab, that the server is returning the correct access control headers from the GimmeProxy API.
Edit: Upon further inspection, I don't seem to see an access control header on this API endpoint.
What you'll need to do in that case, is set up your own API endpoint as a middleman:
Set up an Express API on a VPS (or alternatively an AWS lambda function).
Create an endpoint that makes a request to gimmeproxy.
Your Chrome extension makes a request to this endpoint via Axios.
The endpoint makes a request to the gimmeproxy API via Axios (it is not a browser, so no cross origin policies are enforced).
Your API returns the response to the client.
It is important to note, that your Express API must return the header 'Access-Control-Allow-Origin': '*' or have an origin matching that of your extension.

Docusign - Axios CORS (Working on Postman)

I'm trying to make this API call from my vue.js SPA.
this.$apiCallDocusign.post('/oauth/token', {
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: '{myJWT}'
})
$apiCallDocusign is:
import axios from 'axios'
var h_ds = {}
h_ds = {
"Content-Type": "application/json"
}
const apiUrlDocusign = 'https://account-d.docusign.com'
const apiCallDocusign = axios.create({
baseURL: apiUrlDocusign,
headers: h_ds
})
export default apiCallDocusign
But i get CORS error:
Access to XMLHttpRequest at 'https://account-d.docusign.com/oauth/token' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
It works in Postman or Terminal with curl... Thanks in advance
Several issues here:
The only OAuth flow that may be used from a SPA to DocuSign is the Implicit grant flow. It works fine from a SPA (I use it myself.) JWT grant can't be used since there is no way to protect the needed private key from others.
An alternative is to have a lightweight server app that generates a DocuSign Access Token by using the JWT grant and then returns it to your SPA. Be careful to secure the server app against bad guys.
You will also need to create a private CORS gateway for use by your application since DocuSign doesn't yet support CORS. Docs for creating a private CORS gateway.
To help raise the profile of CORS, please ask your DocuSign contacts
to add your name/organization to internal ticket PORTFOLIO-1100.
CORS is on our roadmap but is not yet scheduled.