[英]getStaticProps not working with getInitialProps in Nextjs
[英]Nextjs getInitialProps not working with NGINX
因此,我有一個Next.js React組件,該組件使用getInitialProps在初始頁面加載之前調用某些數據的后端。 看起來像這樣:
static async getInitialProps({req, query}){
console.log('inside getInitialProps')
if (req){
var pinReturn = await axios.post(process.env.serverADD+'getPinData', {withCredentials: true})
.then(response=>{
console.log('value of response: ', response)
return response.data.pins
})
.catch(error=>{
console.log('value of error: ', error)
return({})
})
}
return {pinData: pinReturn}
}
我認為這很容易解釋-當我的后端是一個簡單的docker容器時它就可以工作。 但是,現在我正在使用nginx和docker-compose旋轉前端和后端。 目前,我的process.env.serverADD
等於http://localhost:80/back/
。
我的NGINX是:
server {
listen 80;
listen [::]:80;
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
server_name example.com www.example.com localhost;
location /back {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://nodejs:8000;
}
location / {
proxy_pass http://nextjs:3000;
}
location ~ /.well-known/acme-challenge {
allow all;
root /var/www/html;
}
}
這是我的docker-compose(這類似於這里的內容: https : //www.digitalocean.com/community/tutorials/how-to-secure-a-containerized-node-js-application-with-nginx-讓我們加密並與docker-compose#step-2-%E2%80%94定義網絡服務器配置 ):
version: '3'
services:
nodejs:
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
container_name: nodejs
restart: unless-stopped
networks:
- app-network
nextjs:
build:
context: ../.
dockerfile: Dockerfile
ports:
- "3000:3000"
container_name: nextjs
restart: unless-stopped
networks:
- app-network
webserver:
image: nginx:mainline-alpine
container_name: webserver
restart: unless-stopped
ports:
- "80:80"
volumes:
- web-root:/var/www/html
- ./nginx-conf:/etc/nginx/conf.d
- certbot-etc:/etc/letsencrypt
- certbot-var:/var/lib/letsencrypt
depends_on:
- nodejs
- nextjs
networks:
- app-network
volumes:
certbot-etc:
certbot-var:
web-root:
driver: local
driver_opts:
type: none
device: /
o: bind
networks:
app-network:
driver: bridge
如果我從curl調用http://localhost:80/back/getPinData
,那么我會得到期望的數據。 它通過nginx路由,命中我的docker-compose,然后路由到我的nodejs應用程序中的正確位置。 但是,如果我從getInitialProps
調用該API,則會收到以下錯誤:
inside getInitialProps
value of error: { Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1104:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80,
config:
{ adapter: [Function: httpAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: [Function: validateStatus],
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
'User-Agent': 'axios/0.18.0',
'Content-Length': 24 },
method: 'post',
url: 'http://localhost:80/back/getPinData',
data: '{"withCredentials":true}' },
request:
Writable {
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
emitClose: true,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
_events:
[Object: null prototype] {
response: [Function: handleResponse],
error: [Function: handleRequestError] },
_eventsCount: 2,
_maxListeners: undefined,
_options:
{ maxRedirects: 21,
maxBodyLength: 10485760,
protocol: 'http:',
path: '/back/getPinData',
method: 'post',
headers: [Object],
agent: undefined,
auth: undefined,
hostname: 'localhost',
port: '80',
nativeProtocols: [Object],
pathname: '/back/getPinData' },
_ended: false,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 24,
_requestBodyBuffers: [ [Object] ],
_onNativeResponse: [Function],
_currentRequest:
ClientRequest {
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: true,
socket: [Socket],
connection: [Socket],
_header:
'POST /back/getPinData HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 24\r\nHost: localhost\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/back/getPinData',
_ended: false,
res: null,
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable: [Circular],
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]: [Object] },
_currentUrl: 'http://localhost:80/back/getPinData' },
response: undefined }
這里發生了什么? 為什么不使用NGINX時,getInitialProps似乎可以工作,而使用反向代理時,為什么不能失敗?
從容器中解析URL時, localhost
不再是您的實際主機。 相反,它是容器本身的回送適配器。
如果嘗試從Docker容器中調用Nginx服務器,則需要使用http://webserver:80/back/getPinData
。
您已經將docker-compose.yml
為使用網橋網絡 ,因此應該可以立即使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.