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

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

http://localhost:8895 is returning This page isn’t working even if everything seems ok

问题

我正在使用MacOS。这是我的Fastify代码:

  1. const fastify = require('fastify')({ logger: true })
  2. fastify.get('/ping', (req, reply) => {
  3. reply.send({
  4. pong: "pong"
  5. })
  6. })
  7. const start = () => {
  8. try {
  9. fastify.listen({ port: 8895 })
  10. } catch (e) {
  11. fastify.log.error(e)
  12. process.exit(1)
  13. }
  14. }
  15. start()

它正在Docker容器中运行:

  1. version: '3'
  2. services:
  3. node-app:
  4. build: .
  5. ports:
  6. - "8895:8895"

这是我的Dockerfile:

  1. FROM node:latest
  2. COPY *.json ./
  3. COPY *.js ./
  4. RUN npm install
  5. CMD ["npm", "run", "start"]

这是我运行的命令:

  1. docker-compose down && docker-compose up --build

一切都在容器内正常工作。我也可以在容器内使用curl,Fastify返回状态码200。但从我的主机请求http://localhost:8895时,出现以下错误:

  1. This page isnt working
  2. 127.0.0.1 didnt send any data.
  3. ERR_EMPTY_RESPONSE

问题出在哪里?

英文:

I am working with MacOs. This is my fastify code

  1. const fastify = require('fastify')({ logger: true })
  2. fastify.get('/ping', (req, reply) => {
  3. reply.send({
  4. pong: "pong"
  5. })
  6. })
  7. const start = () => {
  8. try {
  9. fastify.listen({ port: 8895 })
  10. } catch (e) {
  11. fastify.log.error(e)
  12. process.exit(1)
  13. }
  14. }
  15. start()

It is running inside docker container:

  1. version: '3'
  2. services:
  3. node-app:
  4. build: .
  5. ports:
  6. - "8895:8895"

This is my Dockerfile

  1. FROM node:latest
  2. COPY *.json ./
  3. COPY *.js ./
  4. RUN npm install
  5. 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:

  1. This page isnt working
  2. 127.0.0.1 didnt send any data.
  3. ERR_EMPTY_RESPONSE

What's wrong?

答案1

得分: 2

你需要在listen上添加host选项:

  • 参考链接:https://fastify.dev/docs/latest/Reference/Server/#listentextresolver
  1. const start = () => {
  2. try {
  3. fastify.listen({ host: '0.0.0.0', port: 8895 })
  4. } catch (e) {
  5. fastify.log.error(e)
  6. process.exit(1)
  7. }
  8. }

与expressjs相比,这是一个“默认安全”的选项。

英文:

You need to add the host option on the listen:

  1. const start = () => {
  2. try {
  3. fastify.listen({ host: '0.0.0.0', port: 8895 })
  4. } catch (e) {
  5. fastify.log.error(e)
  6. process.exit(1)
  7. }
  8. }

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:

确定