Phoenix + React 无法发出 HttpGet 请求

Phoenix + React can't make HttpGet request

我在我的应用程序中使用带有 React 的 Phoenix 1.3 版并尝试发出 Get 请求:

httpGet('/api/v1/users')
   .then(function (data) {
     console.log("http get works!!!!");
   })
   .catch(function (error) {
     console.log("nope doesn't work");
   });

其中 httpGet 是:

export function httpGet(url) {
   return fetch(url, {
     headers: buildHeaders(),
   })
   .then(parseJSON);
 }

解析JSON:

export function parseJSON(response) {
  return response.json();
}

buildHeaders():

const defaultHeaders = {
    Accept: 'application/json',
   'Content-Type': 'application/json',
};
function buildHeaders() {
  const authToken = localStorage.getItem('phoenixAuthToken');
  return { ...defaultHeaders, Authorization: authToken };

这是我的路由器:

defmodule App.Web.Router do
   use App.Web, :router

pipeline :browser do
   plug :accepts, ["html", "json"]
   plug :fetch_session
   plug :fetch_flash
   plug :protect_from_forgery
   plug :put_secure_browser_headers
end

pipeline :api do
   plug :accepts, ["json"]
   plug Guardian.Plug.VerifyHeader
   plug Guardian.Plug.LoadResource
end

scope "/", App.Web do
   pipe_through :browser # Use the default browser stack
   get "/*path", PageController, :index 
end

scope "/api", App.Web do
   pipe_through :api

  scope "/v1" do
     post "/users", UserController, :create
     get "/users", UserController, :index
  end
end

我不断收到 httpget 请求失败的错误消息。所以,我的问题是我的路由器出了什么问题? Post,删除请求有效。我相信它与路由器有关,但我找不到确切的问题。任何帮助表示赞赏!

编辑:我得到的服务器响应:

[info] GET /api/v1/current_user
[debug] Processing with App.Web.PageController.index/2
   Parameters: %{"path" => ["api", "v1", "users"]}
Pipelines: [:browser]
[info] Sent 200 in 260µs

和Google开发工具:

Request Method:GET
Status Code:200 OK
Response Headers: Content-Type:text/html; charset=utf-8

您的包罗万象的路由 get "/*path" 匹配所有 GET 请求,包括发送到 /api/v1/users 的请求,因为它出现在 /api/v1/users 路由之前。如果将它移到下方,一切都应该按预期工作:

pipeline :browser do
   ...
end

pipeline :api do
   ...
end

scope "/api", App.Web do
  pipe_through :api

  scope "/v1" do
     post "/users", UserController, :create
     get "/users", UserController, :index
  end
end

scope "/", App.Web do
   pipe_through :browser # Use the default browser stack
   get "/*path", PageController, :index 
end