O
O
Orc2019-07-16 13:25:20
Express.js
Orc, 2019-07-16 13:25:20

Vue.js/Express.js :: How to correctly pass the token to the server in headers?

Stack: vue.js + express.js CORS is configured and running
in server.js . With API / CRUD requests , CORS works great. http.js --------


import Axios from 'axios';

    export default Axios.create({

        withCredentials: true,
        baseURL: 'http://xxx.xxx.xxx.xxx:8080/api',
        timeout: 5000,
        headers: {

            'Content-type': 'application/json'
        }
    });

products.vue
---------------
import http from '../http.js';

    //...

    http.post('/auth/signin', data)
        .then(response => {

            const answer = response.data;
            
            if (response.data.state === 'success') {

               //...

            }
        })
        .catch(e => {

            console.log(e);
        });

server.js
----------
//...

    // Load CORS
    const cors = require('cors');
    const corsOptions = {

        credentials: true,
        origin: 'http://mydomen.ru',
        allowedHeaders: ['Content-Type'],
        optionsSuccessStatus: 200
    };
    app.use(cors(corsOptions));

    //...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-07-16
@z0ddak

For example like this:

headers: {
  'Content-type': 'application/json',
  'Authorization': `Bearer ${token}`,
},

or you can, when receiving a token, put Authorization in the default headers:
axios.defaults.headers.common.Authorization = `Bearer ${token}`;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question