28

I'm new to Vue.js and want to make a request in a component to a restricted api:

  computed: {
    token () {
      return this.$store.getters.getToken; 
    },
   ...

created () {
         axios
        .get( this.BASE_URL + '/profile/me')
        .then( res => {
                    this.profile = res.data;
                    console.log('profile is:', res.data);

          })
          .catch(error => console.log(error))            
    },

The problem is that I don't know how to include the token into the request header. So not surprisingly I get 401 error in response.

And when I try

axios.defaults.headers.common['Authorization'] = this.token;

before the get request I receive OPTIONS /profile/me instead of GET /profile/me in the server logs.

How can I fix it?

Babr
  • 1,971
  • 14
  • 33
  • 47

2 Answers2

31

Axios get() request accept two parameter. So, beside the url, you can also put JWT in it.

axios.get(yourURL, yourConfig)
.then(...)

In your case yourConfig might be something like this

yourConfig = {
   headers: {
      Authorization: "Bearer " + yourJWTToken
   }
}

Also you can read about what you can put in your config here https://github.com/axios/axios. Just search for "Request Config"

Lê Quang Bảo
  • 2,670
  • 2
  • 27
  • 40
  • I get `OPTIONS /profile/me 200` in serve log. and no GET request . Also Browser complains about ` Authorization is not allowed ` despite the fact that I have this in expess: `app.use(function(req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); ...` in express settings. – Babr Sep 12 '18 at 10:19
  • Instead of changing your server behavior, you can fake the domain by installing this extension on your local machine.(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi). Config your server to accept request from different domain lead to some kind of CSRF attack. Also, remember to turn off that extension after developing. – Lê Quang Bảo Sep 12 '18 at 13:56
3

This works for me, try like -

let JWTToken = 'xxyyzz';
 axios
    .get(this.BASE_URL + '/profile/me', { headers: {"Authorization" : `Bearer ${JWTToken}`} })
    .then(res => {
       this.profile = res.data;
       console.log('profile is:', res.data);
      })
      .catch(error => console.log(error)) 
Praveen Poonia
  • 745
  • 10
  • 18
  • I get this error: `Failed to load http://127.0.0.1:3000/profile/me: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.`. Any ideas? – Babr Sep 12 '18 at 10:15
  • When we use custom request headers we will get a CORS preflight. We need to reply to that CORS preflight with the appropriate CORS headers to make this work. like - ` { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); ` – Praveen Poonia Sep 12 '18 at 10:24
  • I know. I have express `app.use(function(req, res, next) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Credentials", "true"); res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT"); res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); next(); });` but still get the error. Any ideas how to fix it? – Babr Sep 12 '18 at 10:26
  • 1
    if you using webpack with vue app, then try this - https://github.com/axios/axios/issues/853#issuecomment-374846375 it will solve the problem by configuring proxy to avoid CORS – Praveen Poonia Sep 12 '18 at 10:41
  • Sorry, not sure how to put that. snippet. I've created the app using vue.cli. And there is a `webpack.config.js` in `/node_modules/@vue/cli-service` but when I put there `"devServer":{ "proxy": { "/": { "target": 'http://127.0.0.1:3000', "pathRewrite": { '^/': '' }, "changeOrigin": true, "secure": false } } }` still get the same error after vue server reload. What could be wrong here? – Babr Sep 12 '18 at 10:48