2

尝试为客户端应用程序创建服务器端 API。客户端完全写在反应上。在开发中使用端口 3000 上的 webdevserver。服务器正在侦听端口 3001。我已将代理添加到package.json客户端应用程序的文件中,如下所示:

{
  "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/"
}

但是一旦我请求服务器 API,它就会失败:

import Request from 'superagent';

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

响应对象为空。如果我尝试使用 3001 端口请求 API - 一切正常。似乎 web-dev-server 没有代理请求,或者我错过了一些额外的配置选项?

4

1 回答 1

2

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.

于 2017-02-14T15:18:46.940 回答