【问题标题】:Proxying requests from client react app to server with create-react-app and webpack dev server使用 create-react-app 和 webpack 开发服务器将来自客户端 react 应用程序的请求代理到服务器
【发布时间】:2017-07-02 20:17:01
【问题描述】:

尝试为客户端应用程序创建服务器端 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 没有代理请求,或者我错过了一些额外的配置选项?

【问题讨论】:

  • 您是否按照docs 的建议尝试改用/api/v1/tasks?另外,我注意到您使用的是 superagent 而不是 fetch api - 切换到后者可能会有所帮助。
  • 试过不同的网址,但同样的问题
  • 如何将您的proxy 更改为http://localhost:3001(丢失最后一个/)?
  • 也尝试过,但没有成功
  • 关于 fetch:尝试使用它,但是一旦我安装了 fetch 并尝试使用它,就会出现很多错误。突然间漏掉了很多库,比如 net、dgram、tap 等。不知道这是什么。

标签: javascript node.js reactjs create-react-app react-fullstack


【解决方案1】:

这对您来说失败的原因是因为您使用 superagent 来执行您的请求。 superagent 发送错误的 Accept 标头以使 create-react-app 代理正常工作。根据create-react-app documentation 中的 cmets,代理设置使用一些启发式方法来处理应该发送到历史 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));
}

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

【讨论】:

  • 感谢您提供如此详细的解释。您提供的代码示例似乎存在问题。它不起作用,我不知道为什么。它只是返回 null 作为响应。但我得到了这个想法并使用request npm 包用于相同目的并将Accept 标头更改为等于application/json 并且它工作正常。
猜你喜欢
  • 2022-06-28
  • 2019-05-30
  • 2018-01-30
  • 2017-09-02
  • 1970-01-01
  • 2018-03-05
  • 2023-03-28
  • 2018-04-21
  • 2017-03-03
相关资源
最近更新 更多