How to receive express headers sent by Xios in React.js

Asked

Viewed 1,371 times

0

My front sends requests with Axios to Node express API this way:

class ServiceRequest {

  constructor() {
    this.api = axios.create({
      baseURL: URL_BASE,
      timeout: 1000,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'x-access-token': 'dgwtvretvrerv',
        'x-access-key': 'eyJhbGciOiJIUzI1'
      }
    });
  }

  create( url, object ) {
    return new Promise( ( resolve, reject ) => {
      this.api.post( url, object )
         .then( response => response.status === 200 ? resolve( response.data ) : reject( response.data ) )
         .catch( error => reject( error.request.response ) );
    });
  }
}

But in my express Node API I cannot receive these values. My header comes this way:

{ host: 'localhost:1234',
  connection: 'keep-alive',
  'access-control-request-method': 'POST',
  origin: 'http://localhost:3000',
  'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
  dnt: '1',
  'access-control-request-headers': 'x-access-key,x-access-token',
  accept: '*/*',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'pt-BR,pt;q=0.9' }

When I try console.log(req.headers['x-access-key']) he prints a undefined.

I also noticed that req.method is coming as OPTIONS, but I’m using POST!

Could someone help me receive / send the headers correctly?

//Edit

I have this middleware that I use in app.use() on my server

const allowCrossDomain = (req, res, next) => {  
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
};
  • Edit your question by adding the code snippet where you make the call to Express

  • I think you’re not in trouble there, because when I test with Postman it works well... I can access the header in cool.

2 answers

1

You are submitting this request through the same website that offers this service?

When a cross source request of type POST, PUT or PATCH is sent by a browser, the browser first sends a request of type OPTIONS for security reasons.

The server must then respond by sending the header Access-Control-Allow-Origin containing the address of your website (or *) to allow the browser to send the POST itself.

  • Client and API are in http://localhost, but both have their own servers running on different ports which are the 3000 and 1234 respectively.

0

You must enable in CORS the header x-access-token:

const allowCrossDomain = (req, res, next) => {  
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type, x-access-key');

  next();
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.