http://localhost:8895 返回“此页面无法使用”,即使一切似乎正常。

huangapple go评论58阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月17日 16:53:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定