简体   繁体   中英

Proxying requests from client react app to server with create-react-app and webpack dev server

Trying to create server side API for the client application. The client is written completely on react. In development is served with webdevserver on port 3000. The server is listening on port 3001. I've added proxy to the package.json file of the client app as following:

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.8.5"
  },
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "react-router": "^3.0.2",
    "superagent": "^3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "proxy": "http://localhost:3001/"
}

but once I am requesting the server API it fails:

import Request from 'superagent';

export function searchTasks(text, callback) {
  Request.get('http://localhost:3000/api/v1/tasks', response => {
    callback(response.body.Search);
  })
}

Response object is null. If I try to request API with 3001 port - everything works fine. It seems web-dev-server is not proxying the requests or, maybe, I missed some additional configuration options?

The reason this fails for you is because you're using superagent to do your requests. superagent sends the wrong Accept header for the create-react-app proxy to work correctly. According to the comments in the create-react-app documentation , the proxy setup uses some heuristics to deal with what should be sent to the history API and what should be proxied.

You can fix this most easily by adding .accept('json') to your request. That's done like so:

import Request from 'superagent';

export function searchTasks(text, callback) {
  Request.get('http://localhost:3000/api/v1/tasks')
    .accept('json')
    .end(response => callback(response.body.Search));
}

Another way is to use the fetch API. You can read more about it (and how to polyfill it for older browsers) in the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM