Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create-react-app proxy works only with fetch api but not in simple get of the browser

I'm using pretty small create-react-app running on port 3000 setup to proxy requests to backend server running on port 8080. If I put in the browser address bar http://localhost:3000/api/me I get back the index.html page but if I use fetch API to get /api/me it try to call to by backend.

The problem is that I have to authenticate with the backend which will set a cookie but since I can't access the login page on http://localhost:3000/login I can't get the cookie.

On a different project which I've eject from create-react-app I have small file to run webpack-dev-server wih the configuration

  proxy: {
    "*": "http://localhost:9191"
  }

which does proxy requests even when put into the browser address bar.

Is it possible to create such setup in create-react-app?

like image 723
Ido Ran Avatar asked Nov 30 '16 19:11

Ido Ran


2 Answers

Closer look into create-react-app code reveal that this is by design:

For single page apps, we generally want to fallback to /index.html. However we also want to respect proxy for API calls. So if proxy is specified, we need to decide which fallback to use. We use a heuristic: if request accepts text/html, we pick /index.html. Modern browsers include text/html into accept header when navigating. However API calls like fetch() won’t generally accept text/html. If this heuristic doesn’t work well for you, don’t use proxy.

Running GET of http://localhost:3000/api/me inside REST Console extension return the correct result.

Further reading about Fetch API and cookies reveal that I have to include the parameter credentials:true to send cookies:

fetch('/api/me', {
  credentials: 'include'
})
like image 190
Ido Ran Avatar answered Nov 03 '22 01:11

Ido Ran


Yes it is possible:

  "proxy": {
    "/api": {
      "target": "<url>",
      "ws": true
    }
  },

See https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#configuring-the-proxy-manually

like image 42
Nick Avatar answered Nov 02 '22 23:11

Nick