[英]create-react-app proxy requests to php backend
我通过$ php -S localhost:8888 -t public
运行Lumen(5.3)API,当我通过邮递员点击任何端点时它会正常工作。 但是,当我尝试卷曲localhost:8888 / v1 / auth / login时,我收到以下错误:
curl:(7)无法连接到localhost端口8888:连接被拒绝
在问这个问题之前我做了一些讨论,有些用户说我可能需要为我的一些路线启用CORS。 所以我继续安装https://github.com/barryvdh/laravel-cors#lumen并将其应用到所有路线。
但是,我仍然无法从终端窗口点击任何端点。
最终目标
最终,目标是将响应应用程序的请求代理到流明后端,但我一直拒绝连接。
代理错误:无法将请求/ v1 / auth / login从localhost:3000代理到http:// localhost:8888 / 。 有关更多信息,请参阅https://nodejs.org/api/errors.html#errors_common_system_errors(ECONNREFUSED )。
是否有可能我在内腔中错误配置了句柄CORS中间件?
更新
我设法通过在请求中注入完整路径来响应应用程序向我的流明API发出请求。 例如,代替/v1/auth/login
,路径现在是http://localhost:8888/v1/auth/login
。 我设法通过添加mode: 'no-cors'
来实现这一点mode: 'no-cors'
到我的fetch:
function login(userData, onError, cb) {
return fetch('http://localhost:8888/v1/auth/login', {
mode: 'no-cors',
method: 'post',
body: JSON.stringify(userData),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.then(parseJSON)
.then(cb)
.catch(onError);
}
没有模式:没有人
理想情况下,我只想return fetch('/v1/auth/login', {
并代理没有模式的请求:no-cors但这似乎不起作用。任何想法为什么?
此外,curl的问题仍然存在。
事实证明,通过启动我的PHP后端与$ php -S localhost:8888 -t public
导致问题首当其冲。 在挖掘了create-react-app问题之后,我发现一个用户在使用php后端时遇到了类似的问题( https://github.com/facebookincubator/create-react-app/issues/800 )。
解决方案是像这样启动服务器: $ php -S 0.0.0.0:8888 -t public
这将允许create-react-app正确地代理对php服务器的请求。 这也让我curl localhost:8888
另外,我需要在我的php.ini文件中取消注释always_populate_raw_post_data = -1
( 警告关于`$ HTTP_RAW_POST_DATA`被弃用 )
我的设置如下:
的package.json
{
"name": "client",
"version": "0.4.2",
"private": true,
"devDependencies": {
"enzyme": "^2.6.0",
"react-addons-test-utils": "^15.4.1",
"react-scripts": "0.7.0"
},
"dependencies": {
"isomorphic-fetch": "^2.2.1",
"react": "^15.4.1",
"react-dom": "^15.4.1",
"react-router-dom": "^4.2.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8888/"
}
从客户端获取
function login(userData, onError, cb) {
return fetch('/v1/auth/login', { // <-- this works correctly now
method: 'post',
body: JSON.stringify(userData),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(checkStatus)
.then(parseJSON)
.then(cb)
.catch(onError);
}
希望这将有助于其他任何遇到类似问题的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.