我在我的应用程序中使用Phoenix 1.3和React并试图获取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);
}
parseJSON:
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请求失败的错误。所以,我的问题是我的路由器出了什么问题?发布,删除请求有效。我相信它与路由器有关,但我找不到确切的问题。任何帮助赞赏!
编辑:来自我得到的服务器的响应:
[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 Dev工具:
Request Method:GET
Status Code:200 OK
Response Headers: Content-Type:text/html; charset=utf-8
答案 0 :(得分:1)
您的全部路由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