我有一个使用 jwt 向 Django 后端进行身份验证的 React 前端。后端工作正常,使用 django View 连接得很好,但是当我尝试代理来自 React 的请求时,它给了我一个 Connection Refused 错误。
Proxy error: Could not proxy request /api/auth/token/obtain/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED).
连接到 http://localhost:8000/api/auth/token/obtain/工作正常。而且用axios发送POST请求也能正常工作,返回token json。但是当我用 Node 代理它时,它不起作用。
在我的 package.json
我有:
"proxy": {
"/api/*": {
"target": "http://localhost:8000"
}
},
编辑:Public repo .如果您安装了 docker,您可以轻松运行。 (使用 1 个图像和 2 个容器)。克隆后只需运行 docker-compose build
,然后运行 docker-compose up
。
Edit2:请求 header :
*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 开发环境和 Django 开发环境都在不同的 docker 容器中运行,所以 localhost
指的是 Node 容器,而不是桥接网络。
所以关键是使用容器链接,这些链接是在使用 docker-compose
时自动创建的,并将其用作主机名。所以我把它改成了
"proxy": {
"/api": {
"target": "http://django:8000"
}
},
只要您使用相同的 docker-compose
命令启动两个容器,这样就可以了,否则您必须在 docker-compose.yml
中手动指定 external_links文件。
关于node.js - react 代理错误 : Could not proxy request/api/from localhost:3000 to http://localhost:8000 (ECONNREFUSED),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50107816/