代理客户端请求通过create-react-app和webpack dev服务器将应用程序反馈给服务器
尝试为客户端应用程序创build服务器端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开发服务器不代理请求,或者,我错过了一些额外的configuration选项?
这个失败的原因是因为你使用superagent
来做你的请求。 superagent
为create-react-app
代理发送错误的Accept
头以正确工作。 根据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)); }
另一种方法是使用fetch
API。 您可以在文档中阅读更多关于它(以及如何为旧浏览器填充它)。
- 创buildReact App + Express.js + Passport.jslogin问题
- 在create-react-app项目中增加JavaScript堆大小
- 即使使用新build的应用程序,create-react-app的“npm start”也不起作用。 在chokidar node_module中抛出错误
- 如何用npm脚本在css文件中编辑相对path?
- 使用Express创build反应应用程序
- 如何通过terminal安装create-react-app
- 用Moment JS创buildReact-App:找不到模块“./locale”
- 在Heroku上使用Rails API部署Create-React-App
- 如何单独加载ES6模块(根据需要)又名。 树在摇晃吗?