How to Fix react cors error in localhost? - javascript

I'm working on a react app. Where I'm requesting for an API by AXIOS. But When I run NPM START to test my app in localhost I'm getting CORS error. Here is the error
Access to XMLHttpRequest at 'https://********.com/trx_status.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field privatekey is not allowed by Access-Control-Allow-Headers in preflight response.
I'm new in react. Please tell me how can I solve this issue. Thank you...

The error is caused by the custom privatekey header that is send to the server. This field has to be included in the Access-Control-Allow-Headers response header from the server. It can be done using:
Access-Control-Allow-Headers: privatekey
when using php the following snippet can be used:
header('Access-Control-Allow-Headers: X-Requested-With, privatekey');

This seems to me like an issue at your server side. So what you could try doing is to try adding the header "Access-Control-Allow-Origin: *".
It would be helpful if you could post it somewhere in jsfiddle or some editor so we can look at it further.
Thanks

Open package.json file, in directory of your App, then add this line (preferably under "private" line, as you can see in the picture below. This also works for any other url if your back-end is not located on your localhost.
"proxy": "http://localhost:3000/",
Remember to restart your server after this change!

For this you will need to allow CORS in your backend code for the URL you will be deploying, and you can use that URL as proxy. You can refer this documentation for detailed instructions.

Related

Cors block while trying to get Instagram access token on client side using react/js

Okay so im trying to get access token im following the main guide provided by facebook app developers which is: https://developers.facebook.com/docs/instagram-basic-display-api/getting-started. Im at step: 5, where i try to exchange my code for access_token. I do post request to https://api.instagram.com/oauth/access_token however i get cors blocked with this error:
Access to XMLHttpRequest at
'https://api.instagram.com/oauth/access_token' from origin
'https://localhost' has been blocked by CORS policy: Request header
field content-type is not allowed by Access-Control-Allow-Headers in
preflight response.
I literlly tried everything. Adding headers to axios, using ngrok to get an actual secure https: and not self made cert (for dev mode ofc). I also changed the app ouath urls. What could the problem be?
Yeap i allowed urls i did everything. I tried https://cors-anywhere.herokuapp.com/https://api.instagram.com/oauth/access_token it didn't work, it says bad request. However i managed to solve it with an extra library called axios-oauth-client: https://www.npmjs.com/package/axios-oauth-client. After implementing this library and instead of doing axios.post(url, data) but using this library and passing the data in there everything works fine and i get the access token. Something with the headers might have been the problem

POSTing to external API throws CORS but it works from Postman

I am using the imgur api to upload images via a node js app.
I am converting images to base64 strings and sending them via Postman works great.
I use node-fetch to make api calls.
const fetch = require('node-fetch')
...
async uploadImage(base64image) {
try {
const url = 'https://api.imgur.com/3/image'
const res = await fetch(url,
{
method: 'POST',
body: { image: base64image },
headers: {
'content-type': 'application/json',
'Authorization': 'Client-ID [my-client-id]',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, Access-Control-Allow-Headers',
'Access-Control-Allow-Methods': 'POST',
}
}
)
console.log(res)
} catch(err) {
console.log(err)
}
}
Error:
Access to fetch at 'https://api.imgur.com/3/image' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response.
I have tried many 'Access-Control-Allow-xxx' headers but none of them worked..
I assume it must be something simple that I am missing. I have been stuck on this for hours please help me.
Browser restricts HTTP requests to be at the same domain as your web page, so you won't be able to hit imgur api directly from the browser without running into CORS issue.
I am converting images to base64 strings and sending them via Postman
works great.
That's because Postman is not a browser, so is not limited by CORS policy.
I have tried many 'Access-Control-Allow-xxx' headers but none of them
worked..
These headers must be returned by the server in response - in your case by the imgur server. You can't set them in the request from browser, so it'll never work.
Error: Access to fetch at 'https://api.imgur.com/3/image' from origin
'http://localhost:3000' has been blocked by CORS policy: Request
header field Access-Control-Allow-Headers is not allowed by
Access-Control-Allow-Headers in preflight response.
Possible solutions to your problem:
If you have access to the backend api you can set the "Access-Control-Allow-Origin" header on the server and let your app access the api - but as you won't have access to the imgur server - you probably can't do that.
Disable CORS in the browser - you can use a plugin like: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en. This workaound should be fine for development. The plugin will disable your CORS settings and you will be able to hit imgur apis.
The third solution is using a proxy. You can setup a small node server using express. You will then hit your own node server, which in turn will hit the imgur api. As node server is not a browser environment, it won't have any CORS issue and you will be able to access imgur API that way. This is also the reason you were able to hit the API from Postman without any issues. As Postman is not a browser environment, it's not limited by CORS policy.
That's because Access-Control-Allow-Headers, Access-Control-Allow-Methods are the headers that is used by the server. The server appends the header by a middleware.
Now, imagine in the server(in this below example an express server) with CORS enabled this kind of (default) headers are getting set:
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Accept');
});
And you are sending Access-Control-Allow-Headers from the client side, and server sees that as a header that is not whitelisted.
So, in headers just use these:
headers: {
'content-type': 'application/json',
'Authorization': 'Client-ID [my-client-id]'
}
It should work fine.
Btw, I think it is working with postman because:
Postman cannot set certain headers if you don't install that tiny postman capture extension.
Browser security stops the cross origin requests. If you disable the chrome security it will do any CORS request just fine.
Also, according to this:
I believe this might likely be that Chrome does not support
localhost to go through the Access-Control-Allow-Origin -- see
Chrome issue
To have Chrome send Access-Control-Allow-Origin in the header, just
alias your localhost in your /etc/hosts file to some other domain,
like:
127.0.0.1 localhost yourdomain.com
Then if you'd access your script using yourdomain.com instead of
localhost, the call should succeed.
Note: I don't think the content type should be application/json it should be like image/jpeg or something. Or maybe don't include that header if it doesn't work.
I have some few observations in my own app that helped me solve this issue. I have a node app as a backend api service and a VueJS built front end. I set my node app with cors with a list of endpoints that are allowed to access my node app. Working on my local machine doesn't give me any errors until I upload it to my server.
here are my environments
Local Environment
Nodejs: 12.16.1
OS: Windows 10
DB: MySQL
NodeJS Server Framework: ExpressJS
Upload Module: Multer
Production Environment
Nodejs: 12.19.0
OS: Ubuntu 20.0.4
DB: MySQL
NodeJS Server Framework: ExpressJS
Upload Module: Multer
nginx
Here are my observations based on my production built app.
When I upload a form with image [500kb and above] [post or put], the cors error shows up but less than that, it all went fine.
If I use form data to send data to the server, I see 2 requests in my network tab, the OPTIONS and the actual request.
The actual request failed but I saw that my content-length is very high which leads me to the conclusion that my request is rejected due to the large amount of data that the client sent which my server may have limited. I know that may be misleading but the solution I did works so I don't know why cors issue is popping up even though the data limit is the issue.
MY SOLUTION:
In my nginx config file, I increased my client_max_body_size to 100M. I believe that nginx has a default of 1MB
Open /etc/nginx/sites-available/your-server-file where your-server-file can be like www.example.com or default.
Add the following line inside the server block. You can set it to any amount you want other than 100M.
server {
client_max_body_size 100M;
...
}
type in sudo systemctl restart nginx to restart nginx.
type in sudo nginx -t to check if change is successful.
Reload your app if you are using pm2 and you are done.
According to this article I used this command in linux and SOME OF(!) cross-origins fixed.
google-chrome --disable-web-security --user-data-dir="/tmp/YOUR_TEMPORARY_PATH"
This will not work if you pass headers from frontend. CORS policy is enabled by browsers. Browser blocks the response when they don't found the headers in response.
Possible Solutions:
You can pass the headers in response (If you have the access of backend or ask the API provider for this)
You can setup a middleware to resolve this.
You can get information from here

How do I set up a GCP App Engine instance with CORS?

I've set up two different GCP App Engine apps. One is an express server (let's call it foo) with the following app.yaml:
runtime: nodejs10
handlers:
- url: /tasks
static_dir: /tasks
http_headers:
Access-Control-Allow-Origin: https://bar.appspot.com/
secure: always
From my bar app, I'm trying to do a fetch call:
const response = await fetch('https://foo.appspot.com/tasks');
Every time I try this, however, Chrome blocks my request with the 'has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.' error. I've also tried just replacing the URL in the http_header with '*' to no avail. Why is this? What am I missing?
Edit: After some more digging, I'm finding that the headers being returned from foo don't even include the Access-Control-Allow-Origin header at all.
Edit 2: I finally bypassed this issue by just using the npm cors package: https://www.npmjs.com/package/cors
Finally bypassed this by using the cors package: https://www.npmjs.com/package/cors. Good luck to you all!
As of May 2020, I had the same issue, css files being blocked by CORS policy on browser, served by Google cloud storage.
And as addressed in this Gcloud wiki page: https://cloud.google.com/storage/docs/configuring-cors#configure-cors-bucket
It worked for me, by setting the CORS on the G storage bucket.
And don't need the handlers stuff config in app.yaml, and I'm not a big fan of YAML btw...

How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

I am working on an app using Vue js.
According to my setting I need to pass to a variable to my URL when setting change.
<!-- language: lang-js -->
$.get('http://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) {
// some code...
});
But when my app hit on URL, it shows the following message.
Failed to load http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26: Redirect from 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26' to 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
In addition to what awd mentioned about getting the person responsible for the server to reconfigure (an impractical solution for local development) I use a change-origin chrome plugin like this:
Moesif Orign & CORS Changer (use to be free but now wants a work email address >_>)
Allow CORS: Access-Control-Allow-Origin
You can make your local dev server (ex: localhost:8080) to appear to be coming from 172.16.1.157:8002 or any other domain.
In case the 2nd plugin link breaks in the future or the plugin writer decides to capitalize off the fame of this thread, open your browser's
plugin marketplace and search "allow cors", there's going to be a
bunch of them.
Thanks all, I solved by this extension on chrome.
Allow CORS: Access-Control-Allow-Origin
If you have control over your server, you can use PHP:
<?PHP
header('Access-Control-Allow-Origin: *');
?>
Ask the person maintaining the server at http://172.16.1.157:8002/ to add your hostname to Access-Control-Allow-Origin hosts, the server should return a header similar to the following with the response-
Access-Control-Allow-Origin: yourhostname:port
Using npm:
To allow cross-origin requests install 'cors':
npm i cors
Add this in the server-side:
let cors = require("cors");
app.use(cors());
When you have this problem with Chrome, you don't need an Extension.
Start Chrome from the Console:
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Maybe you have to close all Tabs in Chrome and restart it.
I will assume that you're a front-end developer only and that you don't have access to the backend of the application (regarding the tags of the question).
Short answer on how to properly solve this in your case? You can't, you'll need somebody else.
What is this about?
You need to understand that CORS is a security thing, it's not just here to annoy you just for fun.
It's purpose is to mainly prevent the usage of a (malicious) HTTP call from a non-whitelisted frontend to your backend with some critical mutation.
You could give a look to this YouTube video or any other one really, but I recommend a visual video because text-based explanation can be quite hard to understand.
You also need to understand that if you use Postman or any other tool to try your API call, you will not get the CORS issue. The reason being that those tools are not Web frontends but rather some server-based tools.
Hence, don't be surprised if something is working there but not in your Vue app, the context is different.
Now, how to solve this?
Depending of the framework used by your backend team, the syntax may be quite different but overall, you'll need to tell them to provide something like Access-Control-Allow-Origin: http://localhost:3000 (or any other port you'll be using).
PS: Using Access-Control-Allow-Origin: * would be quite risky because it would allow anybody to access it, hence why a stricter rule is recommended.
If you're using a service, like an API to send SMS, payment, some Google console or something else really, you'll need to allow your localhost in the dashboard of the service. Ask for credentials to your manager or Tech Lead.
If you have access to the backend, you could it yourself as shown here (ExpressJS in this example): https://flaviocopes.com/cors/
How to hack it in a dirty way?
If you're in a damn hurry and want to get something really dirty, you could use a lot of various hacks a listed in the other answers, here's a quick list:
use any extension who is able to create a middleware and forward the request to the backend (it will work because it's not directly coming from your frontend)
force your browser to disable CORS, not sure how this would actually solve the issue
use a proxy, if you're using Nuxt2, #nuxtjs/proxy is a popular one but any kind of proxy (even a real backend will do the job)
any other hack related somehow to the 3 listed above...
At the end, solving the CORS issue can be done quite fast and easily. You only need to communicate with your team or find something on your side (if you have access to the backend/admin dashboard of some service).
I heavily do recommend trying get it right from the beginning because it's related to security and that it may be forgotten down the road...
The approved answer to this question is not valid.
You need to set headers on your server-side code
app.use((req,res,next)=>{
res.setHeader('Access-Control-Allow-Origin','*');
res.setHeader('Access-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
res.setHeader('Access-Control-Allow-Methods','Content-Type','Authorization');
next();
})
You can also try a chrome extension to add these headers automatically.
Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:
Header set Access-Control-Allow-Origin "*"
And then restart apache.
Altering headers requires the use of mod_headers. Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled.
I had the same problem in my Vue.js and SpringBoot projects. If somebody work with spring you can add this code:
#Bean
public FilterRegistrationBean simpleCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// *** URL below needs to match the Vue client URL and port ***
config.setAllowedOrigins(Collections.singletonList("http://localhost:8080"));
config.setAllowedMethods(Collections.singletonList("*"));
config.setAllowedHeaders(Collections.singletonList("*"));
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
I found solution in this article Build a Simple CRUD App with Spring Boot and Vue.js
You are making a request to external domain 172.16.1.157:8002/ from your local development server that is why it is giving cross origin exception.
Either you have to allow headers Access-Control-Allow-Origin:* in both frontend and backend or alternatively use this extension cors header toggle - chrome extension unless you host backend and frontend on the same domain.
Try running this command in your terminal and then test it again.
curl -H "origin: originHost" -v "RequestedResource"
Eg:
If my originHost equals https://localhost:8081/ and my RequestedResource equals https://example.com/
My command would be as below:
curl -H "origin: https://localhost:8081/" -v "https://example.com/"
If you can notice the following line then it should work for you.
< access-control-allow-origin: *
Hope this helps.
Do specify #CrossOrigin(origins = "http://localhost:8081")
in Controller class.
You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!
You won't believe this,
Make sure to add "." at the end of the "url"
I got a similar error with this code:
fetch(https://itunes.apple.com/search?term=jack+johnson)
.then( response => {
return response.json();
})
.then(data => {
console.log(data.results);
}).catch(error => console.log('Request failed:', error))
The error I got:
Access to fetch at 'https://itunes.apple.com/search?term=jack+johnson'
from origin 'http://127.0.0.1:5500' 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 I realized after a lot of research that the problem was that I did not copy the
right URL address from the iTunes API documentation.
It should have been
https://itunes.apple.com/search?term=jack+johnson.
not
https://itunes.apple.com/search?term=jack+johnson
Notice the dot at the end
There is a huge explanation about why the dot is important quoting issues about DNS and character encoding but the truth is you probably do not care. Try adding the dot it might work for you too.
When I added the "." everything worked like a charm.
I hope it works for you too.
install:
npm i cors
Then include cors():
app.get("/list",cors(),(req,res) =>{
});
In addition to the Berke Kaan Cetinkaya's answer.
If you have control over your server, you can do the following in ExpressJs:
app.use(function(req, res, next) {
// update to match the domain you will make the request from
res.header("Access-Control-Allow-Origin", "YOUR-DOMAIN.TLD");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
https://enable-cors.org/server_expressjs.html
I tried this code,and that works for me.You can see the documentation in this link
var io = require("socket.io")(http, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
})
The reason that I came across this error was that I hadn't updated the path for different environments.
you have to customize security for your browser or allow permission through customizing security. (it is impractical for your local testing)
to know more about please go through the link.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
These errors may be caused due to follow reasons, ensure the following steps are followed. To connect the local host with the local virtual machine(host). Here, I'am connecting http://localhost:3001/ to the http://abc.test Steps to be followed:
1.We have to allow CORS, placing Access-Control-Allow-Origin: in header of request
may not work. Install a google extension which enables a CORS request.*
2.Make sure the credentials you provide in the request are valid.
3.Make sure the vagrant has been provisioned. Try vagrant up --provision this make the localhost connect to db of the homestead.
Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' }
this point is very important.
Another solution to this problem in a specific scenario :
If
AWS APIGW is your backend with authentication enabled and
authentication fails,
your browser may end up complaining about CORS even if CORS is enabled in APIGW. You also need to enable CORS for 4XX as follows
API:YourAPI > Resources > /YourResource > Actions > Enable CORS > Gateway Responses for yourAPI check Default 4XX
Authentication will still fail but it won't look like CORS is the root cause
$.get('https://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) {
// some code...
});
Just put "https" .

CORS Header Error when using Authorization Header

So this is my current code
When I delete the Authorization from the headers the request will be successful, and i get the response. But when I use the Authorization header, it will give me this error.
The server is using Python Django and using this libary for CORS Handling
EDIT 1: This is the python server settings
EDIT 2: Add Browser
I use Chrome Version 53.0.2785.143 m (64-bit)
EDIT 3: Postman response
Just got weird response here. When the backend guy tried from his laptop, he got the complete header. like this:
But when i use my laptop, i got this response:
I'm guessing cors is not allowing the Authorization header. So, lets add that the Authorization entry to CORS_ALLOW_HEADERS
CORS_ALLOW_HEADERS = (
...
'Authorization',
...
)
Solved!
It's caused by the App Enlight plugin for monitoring. When I remove it, everything works without errors :)

Categories

Resources