Huy Nguyen
Huy Nguyen

Reputation: 591

axios cannot send cookie with request even with withCredential: true

I already did the setup on server like this

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header(
    'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization,  X-PINGOTHER'
  );
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
  next();
});

and the axios on client side (react) is like this

axios.defaults.withCredentials = true;
axios('http://127.0.0.1:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err.response);
})

Everything works fine when I test with Postman and type directly to chrome. Any idea what's wrong with my code?

Upvotes: 17

Views: 70494

Answers (9)

Omar Samudio
Omar Samudio

Reputation: 27

you can not use axios in main or preload, to use cookie session need execute from index.js load in browserwindow, config websecurity to true, maybe you can read this article

https://www.geeksforgeeks.org/http-rest-api-calls-in-electronjs/

Upvotes: 0

Eyal Solomon
Eyal Solomon

Reputation: 616

For me it was just adding an empty {} as I was using axios.post -> the first {} in the .post arguments is data argument

From :

const response = await axios.post(
        "/users/logout",
        {
          withCredentials: true,
        }    

To :

const response = await axios.post(
        "/users/logout",
        {},
        {
          withCredentials: true,
        }

Upvotes: 0

Geepy
Geepy

Reputation: 21

I had a similar issue when I was making a put request with axios.

axios.put(‘URL’, {withCredentials: true})

I reconstructed my request too and it worked. Meanwhile, remember to also set your cors config to have the “credentials: true”.

axios(‘URL’, {
  method: ‘PUT‘,
  withCredentials: true
})

Upvotes: 2

Pham Tien Anh
Pham Tien Anh

Reputation: 61

same issue and I fixed it. Follow code:

Backend

const corsConfig = {
  origin: true,
  credentials: true,
};

app.use(cors(corsConfig));
app.options('*', cors(corsConfig))

frontend

axios.defaults.withCredentials = true;

Upvotes: 6

Matt Carlotta
Matt Carlotta

Reputation: 19772

If you plan on using this mulitple times, then just create an axios config:

client/src/utils/axiosConfig.js

import axios from 'axios';

const baseURL = process.env.NODE_ENV === "development"
  ? "http://localhost:3001/"
  : "http://example.com"

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

/* 
  The below is required if you want your API to return 
  server message errors. Otherwise, you'll just get 
  generic status errors.

  If you use the interceptor below, then make sure you 
  return an "err" (or whatever you decide to name it) message 
  from your express route: 
  
  res.status(404).json({ err: "You are not authorized to do that." })

*/
app.interceptors.response.use(
  response => (response), 
  error => (Promise.reject(error.response.data.err))
)

export default app;

client/src/actions/exampleAction.js

import app from '../utils/axiosConfig';

export const exampleAction = () => (
  app.get('orders') // this will be defined as baseURL + "orders" (http://localhost:3001/orders)
    .then(res => console.log(res))
    .catch(err => console.log(err))
)

Then for your API, instead of specifying CORS headers, you can simply use cors wherever you're defining your express middleware:

const cors = require('cors');
const origin = process.env.NODE_ENV === "development" 
  ? "http://localhost:3000" 
  : "http://example.com"

app.use(
  cors({
    credentials: true,
    origin
  }),
);

Upvotes: 12

Zhang Buzz
Zhang Buzz

Reputation: 11088

Now 2020, Chrome add more annoying restricts to cross domain cookies settings, you must set cookies with SameSite to none, otherwise Chrome will refuse to send cookies. More, if you set SameSite, you must set secure.

Below is an example for how to set this change in nginx, it may not work with your situation, but for reference.

proxy_cookie_path / "/; secure; SameSite=none";

Upvotes: 20

ykwx
ykwx

Reputation: 268

I found this article helpful: https://medium.com/acmvit/handling-cookies-with-axios-872790241a9b

But might depend on the server setup.

In client set Axios headers:

headers: {Authorization: `Bearer ${cookie_value}`},
withCredentials: true,
crossDomain: true

Upvotes: -2

masoud nazarpoor
masoud nazarpoor

Reputation: 17

axios.post('http://localhost:5000/api/auth/login',{ userEmail, userPassword },{
        withCredentials: true,
      })


const cors = require("cors");
expressApplication.use(cors({
 origin: ["http://localhost:2000", "http://localhost:3000"],
 credentials: true
}));

Upvotes: 0

Huy Nguyen
Huy Nguyen

Reputation: 591

I figure out my mistake. Change axios code to

axios.defaults.withCredentials = true;
axios('http://localhost:3001/orders', {
  method: 'GET',
  withCredentials: true
}).then(res => {
     console.log(res);
   }).catch(err => {
     console.log(err.response);
   })

I still want to ask why does this change help so any answer will be appreciated

Upvotes: 6

Related Questions