如何使用Application和Plug.Router通过Elixir监听端口

问题描述 投票:0回答:0

我有这个申请文件:

defmodule MyApi do
  use Application

  def start(_type, _args) do
    children = [
      MyApi.Router
    ]

    opts = [strategy: :one_for_one, name: MyApi.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

然后是一个路由器文件,如下所示:

defmodule MyApi.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  # Dummy data to store items in memory
  @items [
    %MyApi.Item{id: 1, name: "Item 1", description: "Description for Item 1"},
    %MyApi.Item{id: 2, name: "Item 2", description: "Description for Item 2"}
  ]

  # Route to get all items
  get "/api/items" do
    send_resp(conn, 200, Jason.encode!(@items))
  end

  # Handle requests to unknown routes
  match _ do
    send_resp(conn, 404, "Not found")
  end
end

但是当我运行

ies -S mix
时,项目没有侦听端口。 我想卷曲并走这条路线:

bash-3.2$ curl http://localhost:4000/api/items
curl: (7) Failed to connect to localhost port 4000 after 9 ms: Connection refused

有人知道如何监听端口并连接路由器吗?

elixir elixir-mix plug ies
© www.soinside.com 2019 - 2024. All rights reserved.