I'm using Reactjs and using API through AJAX in javascript. How can we resolve this issue? Previously I used CORS tools, but now I need to enable CORS.
What Is CORS? CORS is a technique that allows you to make an ajax request to a server of a different domain. This is very useful if you want to consume an API directly on your client — something that is absolutely needed if you're writing a Jamstack web app.
there are 6 ways to do this in React,
number 1 and 2 and 3 are the best:
1-config CORS in the Server-Side
2-set headers manually like this:
resonse_object.header("Access-Control-Allow-Origin", "*");
resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
3-config NGINX for proxy_pass which is explained here.
4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)
5-bypass the cross-origin-policy with URL bellow(only for development)
"https://cors-anywhere.herokuapp.com/{type_your_url_here}"
6-use proxy
in your package.json
file:(only for development)
if this is your API: http://45.456.200.5:7000/api/profile/
add this part in your package.json
file:
"proxy": "http://45.456.200.5:7000/",
and then make your request with the next parts of the api:
React.useEffect(() => {
axios
.get('api/profile/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
});
It is better to add CORS enabling code on Server Side. To enable CORS in NodeJS and ExpressJs based application following code should be included-
var app = express();
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Possible repeated question from How to overcome the CORS issue in ReactJS
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 temporary solve this issue by a chrome plugin called CORS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With