Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

express - Enabling CORS in Create React App utility

I need to use CORS node module in React created using create-react-app utility.

Since its a utility I am not able to tweak inside and inject CORS into preconfigured EXPRESS module.

How can we achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are needing this for development and wanting to access an api from your react app but getting an error like this-

Failed to load http://localhost:8180/tables: 
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8180'
that is not equal to the supplied origin. Origin 'http://localhost:3000' is
therefore not allowed access. Have the server send the header with a valid
value, or, if an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.

then you can get the create-react-app server to proxy your request to your api server quite easily.

create-react-app uses the webpack development server to serve your react app.

So if your react app is being served from http://localhost:3000 and the api you want to connect to is at http://localhost:8180/tables you can simply add a proxy value into your react app's package.json file like this-

proxy: "http://localhost:8180",

then from your react app call your api like

fetch('/tables').then(....)

the request will be sent to the create-react-app server which will send it on to the api server and return the results for you.

Full details here Proxying API Requests in Development


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...