Nuxt.js 在 asyncData 中 POST 到解析服务器会导致跨源错误

Nuxt.js POSTing to a parse server inside asyncData results in cross-origin error

我正在使用 nuxt 构建一个从解析服务器获取数据的客户端。 在我的 index.vue 中,我正在向 asyncData 中的解析服务器发送请求。我在 localhost:3000.

的开发服务器上

这是我的 index.vue 文件的一部分

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

        user.set('email', 'email@company.com')
        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))
       }
    }
}

我在 Chrome 浏览器(顺便说一句,我正在使用 Chrome)控制台上收到此错误

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.

我尝试将 cors 作为中间件添加到 server/index.js 中,如下所示

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

但没有任何改变。如何克服 'ever-present' Access-Control-Allow-Origin 错误。

在@Nicolas Pennec 的回答后更新

我尝试使用 google 功能创建登录并更改了我的 nuxt.config.js 配置并添加了以下内容:

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

它通过 google 正确验证并重定向回我的登录路径。它遇到错误并在控制台上显示以下内容:

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

http://localhost:3000/https://api.parse.com/ 的 CORS 警告不是问题,而是正常的安全警告。它不依赖于 Nuxt,而是依赖于你的浏览器。

推荐使用官方@nuxt/axios模块+proxy配置,轻松避免CORS问题

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


1/ 安装模块:

yarn add @nuxtjs/axios 

npm install @nuxtjs/axios

2/ 在你的 nuxt.config.js:

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

  // ...
}

3/ 通过axios代理调用

更新您的 Parse 配置以调用 POST http://localhost:3000/api/1/users 而不是 POST https://api.parse.com/1/users

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

或相对路径:

Parse.serverURL = '/api'