首页 文章

来自客户端的代理请求使用 create-react-app 和 webpack dev 服务器将应用程序响应到服务器

提问于
浏览
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);
  })
}

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

1 回答

  • 2

    这对您失败的原因是因为您使用superagent来处理您的请求。 superagent发送错误的Accept标头以使create-react-app代理正常工作。根据create-react-app 文件中的注释,代理设置使用一些启发式方法来处理应该发送到历史 API 的内容以及应该代理的内容。

    您可以通过在请求中添加.accept('json')来轻松解决此问题。这样做是这样的:

    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));
    }
    

    另一种方法是使用 API。您可以在文档中阅读有关它的更多信息(以及如何为旧版浏览器对其进行填充)。

相关问题