bhanu
bhanu

Reputation: 218

Cannot send httponly cookie to express server from react js

I am working on a react app which receives httponly cookie from third party website.

I am able to see the cookie in Chrome developer console. I am trying to send this cookie to backend of my app, built in expressjs, so that I can read the cookie. I am using fetch to send a GET request to the app while including the prop below:

Credentials: 'include' 

In the express server, am allowing my front-end inside CORS and also set credentials equal to true.

Issue:
In request header of my express server, I can't see the httponly cookie.

Can anyone guide me how can I send httponly and get it inside express server?

Upvotes: 3

Views: 2135

Answers (2)

Viral Patel
Viral Patel

Reputation: 1156

The first thing is allow our Express application to be able to receive requests from the host on which the Fetch API makes the calls in our situation it makes them from https://localhost:8080

const express = require('express');
const cors = require('cors');

app.use(cors({
origin: 'http://localhost:8080',
credentials: true
}));

The last thing is to create a fetch request via the Fetch API from [https://localhost:8080] to [http://localhost:9090/example]:

fetch('http://localhost:9090/example',{
method: ‘GET’,
credentials: 'include'
});

And now no matter that we made the request from another host ,we receive the cookies

Upvotes: 0

user14080657
user14080657

Reputation: 128

On client you must enable credentials as well. There is axios module to make requests with credentials. Example of usage:

import axios from 'axios'

const instance = axios.create({
  withCredentials: true,
  baseURL: API_SERVER
})

instance.get('todos')

In other way, you could provide cookie with XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

XMLHttpRequest

Upvotes: 2

Related Questions