DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

1

Dealing with CORS in ReactJS

In this post we will discuss 2 methods to resolve the issue 'Access to fetch at 'Client' from origin 'Server' has been blocked by CORS policy, NO 'Access-Control-Allow-Origin' header is present on the requested resource...'

For security reasons, The Same-Origin Policy is implemented on your web browser to block malicious attempts to access data, because of this, when we build a client on localhost:3000 and server on localhost:8000 for example we face this CORS issue.

In ReactJs we can use the proxy property on package.json file to resolve this as shown below (125.0.0.1:500 being the server URL)

"proxy":"http://127.0.0.1:5000"

However if we are to resolve this from the server side then, go to the particular endpoint we need cors allowed, then add 'res.set('Access-Control-Allow-Origin','/ClientURL)'

`app.get('/cors', (req, res) => {
res.set('Access-Control-Allow-Origin', 'http://localhost:5000');

})`

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️