Skip to content

Call API Request from Client-side to use cookie for Authorization #828

Closed

Description

@dzuncoi

Description

I am new to React and decide to use create-react-app for my next project. Now I have an api server at myapi.domain.com and it is authorized by using cookie. In my react project, I use fetch to make request, for example, at myapi.domain.com/v1/getData. When I compare this request with the request I type directly to browser address, I can see a difference.

Expected behavior

The connect.sid value in Cookie field in 2 requests headers are the same.

Actual behavior

The connect.sid value in Cookie field in 2 requests headers are different, so my api server cannot authorize the request.
I assume that when using fetch, the request is not called from client-side, so it cannot get the cookie stored in browser.

So in this case, how can I call a request from client-side (to use cookie stored in browser)?

Sorry for my bad English and explanation.

Activity

  1. shrynx commented on Oct 3, 2016

    @shrynx
    Contributor

    Can you explain the issue a bit further, and maybe provide screen shots of failed request. Though my initial guess, connect session uses httpOnly cookie.
    One way would be to disable it.
    eg

    app.use(express.session({
        secret: 'mySecret',
        cookie: { httpOnly: false }
    }));

    But it is advisable to use same-origin ( Only send cookies if the URL is on the same origin as the calling script) or include (Always send cookies, even for cross-origin calls.)
    Please refer these documentations

  2. shrynx commented on Oct 3, 2016

    @shrynx
    Contributor

    Also i would recommend to use , axios (https://github.com/mzabriskie/axios) , it has inbuilt support for promises, and provides syntactic sugar. with axios you would have to pass something like :

    axios.get('http://my.url', {
        withCredentials: true
    })
    .then( (response) => {
        console.log(response.data)
    })
  3. dzuncoi commented on Oct 3, 2016

    @dzuncoi
    Author

    @shrynx Thanks for your quick responses, especially withCredentials: true in the 2nd one, now I use credentials: 'include' in fetch and problem is solved.
    Thanks.

  4. locked and limited conversation to collaborators on Jan 22, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions