From 6c0dd2b5388d97c884d75119349df2746e902453 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 21 Oct 2017 14:12:51 -0500 Subject: [PATCH] Add Proxy To An API Server In Development With CRA as a react til --- README.md | 3 +- ...o-an-api-server-in-development-with-cra.md | 32 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 react/proxy-to-an-api-server-in-development-with-cra.md diff --git a/README.md b/README.md index d1b3745..0ec36c2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_578 TILs and counting..._ +_579 TILs and counting..._ --- @@ -411,6 +411,7 @@ _578 TILs and counting..._ - [Force A Component To Only Have One Child](react/force-a-component-to-only-have-one-child.md) - [Inline Style Attributes Should Be Camel Cased](react/inline-style-attributes-should-be-camel-cased.md) - [Passing Props Down To React-Router Route](react/passing-props-down-to-react-router-route.md) +- [Proxy To An API Server In Development With CRA](react/proxy-to-an-api-server-in-development-with-cra.md) ### Ruby diff --git a/react/proxy-to-an-api-server-in-development-with-cra.md b/react/proxy-to-an-api-server-in-development-with-cra.md new file mode 100644 index 0000000..3ab03d0 --- /dev/null +++ b/react/proxy-to-an-api-server-in-development-with-cra.md @@ -0,0 +1,32 @@ +# Proxy To An API Server In Development With CRA + +[create-react-app](https://github.com/facebookincubator/create-react-app) is +a great way to bootstrap a React project, especially if you are building a +single-page app. When building an SPA, you more likely than not will have a +backend API that you interact with. + +You can set up your React app to interact with that backend API server in +development using the `proxy` configuration in `package.json`. + +```json +// package.json + ... + "proxy": "http://localhost:4000", +} +``` + +This will allow you to keep your API calls nice and clean. + +```javascript +fetch("/api/session", ... +``` + +No need to manage some sort of _host URL_ environment variable. + +Additionally, this will remove an CORS issues because the `webpackDevServer` +will be proxying any paths that it doesn't recognize to the host and port +that you've specified. + +See [the `create-react-app` +docs](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development) +for more details.