0
votes

I am using nuxt to build a client that fetches data from parse server. In my index.vue I am sending request to the parse server inside asyncData. I am on development server serving at localhost:3000.

Here is a part of my index.vue file

export default {
    asyncData() {
        let user = new Parse.User()

        user.set('email', '[email protected]')
        user.set('username', 'sample_user')
        user.set('created_at', '2018-04-04')
        user.set('updated_at', '2018-04-04')
        return user
          .save()
          .then(response => console.log(response))
       }
    }
}

I am getting this error on my Chrome browser's (I am using Chrome by the way) console

POST https://api.parse.com/1/users 410 Access to XMLHttpRequest at 'https://api.parse.com/1/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried adding cors as middleware to server/index.js as follows

const cors = require('cors')
app.use(cors())

But nothing changed. How can I overcome the 'ever-present' Access-Control-Allow-Origin error.

UPDATE After @Nicolas Pennec's answer

I tried creating a sign in with google feature and changed my nuxt.config.js configuration and added the following:

auth: {
    strategies: {
      google: {
        client_id:
          '****.apps.googleusercontent.com'
      }
    },
    redirect: {
      login: '/login',
      logout: '/',
      callback: '/login',
      home: '/'
    }
  }

It authenticates with google properly and redirects back to my login route. It encounters error and shows the following on the console:

OPTIONS https://www.googleapis.com/oauth2/v3/userinfo 403
Access to XMLHttpRequest at 'https://www.googleapis.com/oauth2/v3/userinfo' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
[ERROR] [AUTH] Error: Network Error
1

1 Answers

5
votes

CORS warning from http://localhost:3000/ to https://api.parse.com/ is not an issue, but a normal security warning. It does not depend on Nuxt but on your browser.

I recommend you to use the official @nuxt/axios module + the proxy configuration to easily avoid CORS issue.

See https://axios.nuxtjs.org && https://github.com/nuxt-community/axios-module


1/ Install module:

yarn add @nuxtjs/axios 

or

npm install @nuxtjs/axios

2/ Configure module in your nuxt.config.js:

module.exports = {
  modules: [
    '@nuxtjs/axios'
  ],
  axios: {
    proxy: true
  },
  proxy: {
    '/api': 'https://api.parse.com/'
  },

  // ...
}

3/ Call through axios proxy

Update your Parse configuration to call POST http://localhost:3000/api/1/users instead of POST https://api.parse.com/1/users

Parse.serverURL = 'http://localhost:3000/api'

or with a relative path:

Parse.serverURL = '/api'