我有一个React前端,它使用jwt与Django后端进行身份验证。后端可以正常工作,并且使用django视图可以正常连接,但是当我尝试代理来自React的请求时,它给了我Connection Refused错误。
代理错误:无法将请求/ api / auth / token / obtain /从localhost:3000代理到http:// localhost:8000(ECONNREFUSED)。
连接到http:// localhost:8000 / api / auth / token / obtain /正常工作。使用Axios发送POST请求也可以正常工作,并返回令牌json。但是,当我用节点代理它时,它不起作用。
在我的package.json我有:
package.json
"proxy": { "/api/*": { "target": "http://localhost:8000" } },
编辑: 公共回购。如果安装了docker,则可以轻松运行。(使用1张图片和2个容器)。克隆后才运行docker- compose build,然后docker-compose up。
docker- compose build
docker-compose up
Edit2:请求标头:
*General* Request URL: http://localhost:3000/api/auth/token/obtain/ Request Method: POST Status Code: 500 Internal Server Error Remote Address: [::1]:3000 Referrer Policy: no-referrer-when-downgrade *Response Headers* HTTP/1.1 500 Internal Server Error X-Powered-By: Express Date: Mon, 30 Apr 2018 21:23:17 GMT Connection: keep-alive Transfer-Encoding: chunked *Request Headers POST /api/auth/token/obtain/ HTTP/1.1 Host: localhost:3000 Connection: keep-alive Content-Length: 45 Pragma: no-cache Cache-Control: no-cache Origin: http://localhost:3000 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 Content-Type: application/json Accept: */* Referer: http://localhost:3000/login Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,fr;q=0.8,ja;q=0.7
因此,问题在于,由于Node dev环境和Django dev环境都在单独的docker容器中运行,因此localhost是指节点容器,而不是桥接网络。
localhost
因此,关键是要使用容器链接,当使用时会自动创建容器链接docker-compose,并将其用作主机名。所以我改成
docker-compose
"proxy": { "/api": { "target": "http://django:8000" } },
只要您使用相同的docker-compose命令启动两个容器,就可以了,否则,您必须在docker- compose.yml文件中手动指定external_links 。
docker- compose.yml