Is there a way to determined why calling my API endpoint from a single page application fails but when calling it from POSTMAN it works?
Set cookie by logging in:
fetch("http://localhost:4000/api/session", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
email: "test3@test.com",
password: "1234",
}),
})
.then((res) => res.json())
.then((res) => console.log(res));
Response headers received:
HTTP/1.1 200 OK
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
access-control-expose-headers:
cache-control: max-age=0, private, must-revalidate
content-length: 87
content-type: application/json; charset=utf-8
date: Sun, 02 May 2021 11:25:13 GMT
server: Cowboy
vary: Origin
x-request-id: Fns8OscbqBybNl8AABXH
set-cookie: token=SFMyNTY.g2gDbQAAACQwOGEwOTFmMC1hNzNiLTRlMGMtYjIwOC1lN2UxMTlkNWRmOGFuBgCcRtMseQFiAAFRgA.81ytoRjjwFJDaNSW1RPRB27J3sf6Vx71nOXfuFks08g; path=/; expires=Sun, 09 May 2021 11:25:14 GMT; max-age=604800; HttpOnly
Function that sets the cookie in the response headers:
def create(conn, %{"email" => email, "password" => password}) do
with {:ok, %User{} = user} <- Accounts.authenticate_user(email, password),
token <- Token.generate_token(user) do
conn
|> put_resp_cookie("token", token, http_only: true, max_age: 604_800)
|> render("auth.json", user: user)
end
end
When accessing a protected endpoint, it fails since I have a plug that checks for “token” cookie and halt if the value is nil
The protected endpoint is just a test GET route
fetch("http://localhost:4000/api/users/1", {
credentials: "include",
})
.then((res) => res.json())
.then((res) => console.log(res));
Response headers:
HTTP/1.1 401 Unauthorized
access-control-allow-credentials: true
access-control-allow-origin: http://localhost:3000
access-control-expose-headers:
cache-control: max-age=0, private, must-revalidate
content-length: 56
content-type: application/json; charset=utf-8
date: Sun, 02 May 2021 11:25:19 GMT
server: Cowboy
vary: Origin
x-request-id: Fns8PB0iFMCQKBEAABBI
Upon inspecting Cookies tab in browser dev tools, it says No cookies for this request
.
Can anyone guide me if there are any mistakes I do?
Thank you very much.