英文:
http://localhost:8895 is returning This page isn’t working even if everything seems ok
问题
我正在使用MacOS。这是我的Fastify代码:
const fastify = require('fastify')({ logger: true })
fastify.get('/ping', (req, reply) => {
reply.send({
pong: "pong"
})
})
const start = () => {
try {
fastify.listen({ port: 8895 })
} catch (e) {
fastify.log.error(e)
process.exit(1)
}
}
start()
它正在Docker容器中运行:
version: '3'
services:
node-app:
build: .
ports:
- "8895:8895"
这是我的Dockerfile:
FROM node:latest
COPY *.json ./
COPY *.js ./
RUN npm install
CMD ["npm", "run", "start"]
这是我运行的命令:
docker-compose down && docker-compose up --build
一切都在容器内正常工作。我也可以在容器内使用curl,Fastify返回状态码200。但从我的主机请求http://localhost:8895
时,出现以下错误:
This page isn’t working
127.0.0.1 didn’t send any data.
ERR_EMPTY_RESPONSE
问题出在哪里?
英文:
I am working with MacOs. This is my fastify code
const fastify = require('fastify')({ logger: true })
fastify.get('/ping', (req, reply) => {
reply.send({
pong: "pong"
})
})
const start = () => {
try {
fastify.listen({ port: 8895 })
} catch (e) {
fastify.log.error(e)
process.exit(1)
}
}
start()
It is running inside docker container:
version: '3'
services:
node-app:
build: .
ports:
- "8895:8895"
This is my Dockerfile
FROM node:latest
COPY *.json ./
COPY *.js ./
RUN npm install
CMD ["npm", "run", "start"]
This is the command I run to work:
> docker-compose down && docker-compose up --build
Everything is working inside the container. I can make also curl inside the container and fastify returns 200. But from my host, requesting http://localhost:8895
, I am getting:
This page isn’t working
127.0.0.1 didn’t send any data.
ERR_EMPTY_RESPONSE
What's wrong?
答案1
得分: 2
你需要在listen
上添加host
选项:
- 参考链接:https://fastify.dev/docs/latest/Reference/Server/#listentextresolver
const start = () => {
try {
fastify.listen({ host: '0.0.0.0', port: 8895 })
} catch (e) {
fastify.log.error(e)
process.exit(1)
}
}
与expressjs相比,这是一个“默认安全”的选项。
英文:
You need to add the host
option on the listen
:
const start = () => {
try {
fastify.listen({ host: '0.0.0.0', port: 8895 })
} catch (e) {
fastify.log.error(e)
process.exit(1)
}
}
This is a "security by default" option compared to expressjs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论