This question already has answers here:
Access from origin 'https://example.com' has been blocked even though I've allowed https://example.com/
(2 answers)
Closed 12 days ago.
I am developing an app with my own sever, i configured my cors with to by client-side host only. Everything seems to be fine i can request data from my database using the GET, but whenever my trying to POST or create, I always have "Response to preflight request doesn't pass access control check:". Please what am I doing wrong? Below is my code
My server-side
const allowedOrigins = [
'http://localhost:3000/'
]
const CorsOptions = {
origin: allowedOrigins,
Credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type'],
optionsSuccessStatus: 204
}
const cors = require('cors')
const CorsOptions = require('./config/CorsOptions')
app.use(cors(CorsOptions))
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
My client-side
const response = await fetch('http://localhost:8000/workout', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type':'application/json'
},
})
const json = await response.json()
if(!response.ok){
errors(json.message)
}
if(response.ok){
reset(data)
console.log('New Workout added successfully', json)
}
The error
Access to fetch at 'http://localhost:8000/workout' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The GET request works perfectly with all these setting above, but for some reason the POST or any other request always gives me this error
I havent done anything yet, i would appreciate any help.
If you're using Chrome to debug your application, then that could be why, since Chrome doesn't support making POST requests from localhost. A bug report was made for this, but it was marked as WontFix, so it's likely not going to change any time soon.
This extension circumvents the issue by setting the Access-Control-Allow-Origin header to *, along with some other stuff.
You may also want to consider this npm package, since you're already using Express.
Hope this helps!
Most likely a permissions issue,
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Configuring CORS headers into server-side code to allow requests from the local host
This header specifies which domains are allowed to make requests to your server.
Related
I am working on a Google Chrome extension to block a subset of images from posts in a user's Reddit feed based on some backend computer vision run in Python in Google Cloud Storage. The Python code takes a single argument (the URL of an image in Reddit), which is passed in JavaScript via:
const api_url = https://<my-google-chrome-url>
var curUrl = $(this).attr("src")
fetch(api_url,{
method: 'POST',
body: JSON.stringify(curUrl),
headers: {
'Content-Type': 'application/json'
},
})
.then(data => {console.log(data)})
When the extension's code runs, I get the following in the console:
Access to fetch at 'https://this-is-the-path-to-my-google-cloud-function' from origin 'https://www.reddit.com' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have tried multiple solutions, enumerated below:
I have followed the instructions here, such that by using Google's gsutil, I am able to confirm the following to be true for the bucket that my function lives in: [{"maxAgeSeconds": 3600, "method": ["GET", "POST"], "origin": ["https://www.reddit.com"], "responseHeader": ["Content-Type"]}]. I have also tried having ["*"] as my origin, to no avail.
I have also tried using in my fetch, mode: no-cors with no success.
Any suggestions or solutions would be greatly appreciated!
For what you mention, the CORS error in this case seems to come from the Cloud Function.
In order to address this, you should configure CORS for the Cloud Function, not Cloud Storage.
CORS consists of the preflight request and the main request. In your function you should check for preflight request by checking if the request's method is OPTION and if so, respond the appropriate headers. Here is a sample:
def cors_enabled_function(request):
# For more information about CORS and CORS preflight requests, see
# https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
# for more information.
# Set CORS headers for the preflight request
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# Set CORS headers for the main request
headers = {
'Access-Control-Allow-Origin': '*'
}
return ('Hello World!', 200, headers)
For more information, you can read the docs
I'm running my Vue app locally from http://localhost:8080 and I keep getting a slew of CORS errors, I've added the Access-Control-Allow-Origin header as seen blow but keep getting the following warning:
' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
const graphCall = () => {
let tokenOptions = {
method: 'POST',
uri: 'https://login.microsoftonline.com/**key**/oauth2/v2.0/token',
headers: {
'Access-Control-Allow-Origin': 'http://localhost:8080',
'contentType': 'application/x-www-form-urlencoded'
},
form: {
grant_type: VUE_APP_GRANT_TYPE,
client_secret: VUE_APP_CLIENT_SECRET,
scope: VUE_APP_SCOPE,
client_id: VUE_APP_CLIENT_ID
}
};
return rp(tokenOptions)
.then(data => {
console.log(data)
}).catch((err) => {
console.log(err);
});
};
I've tried adding mode: 'no-cors' but just get the following - Error: Invalid value for opts.mode
I've also tried '*' as the access control origin but to no avail.
Is there a way through this CORS nightmare as we need to make this call to retrieve a key!
The server has to allow your origin, in this case http://localhost:8080. Often in scenarios where you are interacting with a provider, in the admin portal where you create the tokens, you also have to specify the domain from which you intend on calling it from.
If this is not the case you may be triggering CORS because you are using a header not on the CORS safe list.
https://fetch.spec.whatwg.org/#cors-safelisted-request-header
Access-Control-Allow-Origin is normally the header supplied by the server on a response, it is not meant to be sent on the request.
The following link helped me understand CORS better.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Do note that allowing the origin of * is fine for development but not recommended for production applications.
i get this fail on chrome:
Access to fetch at 'http://******/places?holiday_type=resort¤cy=EUR&checkin=2019-11-01&checkout=2019-11-10&groups[]=1'
from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.
My Code is:
getPlaces = async () => {
try {
let response = await fetch(`${BASE_URL}/places?holiday_type=resort¤cy=EUR&checkin=2019-11-01&checkout=2019-11-10&groups[]=1`,
{
method: 'GET',
headers: new Headers({
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
'Access-Control-Request-Method': 'GET, POST, DELETE, PUT, OPTIONS',
'Authorization': 'Basic ' + Base64.encode(apiuser + ':' + apipassword) ,
}),
})
console.log(response)
} catch (error) {
console.log(error)
}
}
External APIs often block requests like this. I would guess that you are using something like an API-Key for your request which includes payment based on your calls. The problem is that every user can read your key when you call the API in your frontend. Thats why the server is block these.
You need to make a server on your own (e.g. with node.js), call your backend API and then "forward" your request the public API with your secret API key.
Server-to-Server requests won't be blocked and your users can't exploit your API key.
You should also make sure to that your backend server doesn't accepts request which is not your frontend if you want to make it public.
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross-domain.
You can temporarily solve this issue by a chrome plugin called CORS.
copied from: How to allow CORS in react.js?
Reference: How to overcome the CORS issue in ReactJS?
I have my application running locally on my computer and it is trying to connect to my remote nodeJS/Express server. I have set the headers in my remote server.
Main question: How do I allow my remote server to accept requests coming from my localhost with parameters? People have told me that my request will not work because the requested URL and the server URL do not share the same domain. The request is coming from my localhost and it is trying to access my remote node/express server. This transaction works when I remove the params in the request but does NOT work when I have the params.
This is how I set headers in my remote server to accept all requests:
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:9000");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if(res.headersSent) {
console.log("Headers sent");
}
else {
console.log("Headers not sent");
}
next();
});
Also, the res.headersSent keeps evaluating to false even though I can see the headers set in my Google network tab. Why is this value returning false?
This is how I am making my GET request to my server from my localhost:
var req = $http({
url: 'https://20161128t135355-dot-jarvis-hd-live-2.appspot-preview.com/read-message',
method: 'GET',
cache: false,
params: {last_updated: last_updated_time}
});
This post was not helpful How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js
I think the params is causing the error, because it works fine when I take it out. I get this error:
XMLHttpRequest cannot load https://20161128t135355-dot-jarvis-hd-live-2.appspot-preview.com/read-message?last_updated=0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 502.
All the solutions say to add/set the header and as you can see I have done that but my application still gives me the same error when I include params in the request. What should I do differently?
So that means your problem is that your server side code throws an error when you add params to the request. You need to debug that. The CORS stuff is almost certainly irrelevant.
This issue is not a CORS issue, it has something to do with my params request. To fix this, I had to configure body-parser like so:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
This helps when sending JSON data to the client from the server or vice versa. You can find more information here: http://junerockwell.com/difference-parameters-query-strings-express-js/
This question already has answers here:
Origin is not allowed by Access-Control-Allow-Origin
(18 answers)
Closed 6 years ago.
I am using webpack angular2 starter kit (https://github.com/AngularClass/angular2-webpack-starter) for my application and now i have an issue.
I try to make get call
getSomeData(): Observable<any> {
let url = here is my api URL;
let headers = new Headers({ 'Content-Type': 'application/json; charset=utf-8', "Access-Control-Allow-Origin": "*", 'dataType': 'json', });
let options = new RequestOptions({ headers: headers });
return this._http.get(url, options).map(res => res.json());
}
And I have next error
XMLHttpRequest cannot load (my URL) Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405.
This Api (It using firebird) returns XML by default, maybe this cause a problem.
How to make that always came JSON?
How to fix this problem with CORS?
This issue is at the server side. The latter must return a Access-Control-Allow-Origin header in the response of the HTTP call.
Most of time, there are tools you can plug into your server application to do this for you. The server knows that CORS headers must be returned when the client sends a Origin header (automatically added by the browser).
See this article for more details about CORS:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/