Rails 5.1 API CORS 问题

Rails 5.1 API CORS problems

我有一个 rails 5.1.6 api 生成 json。我有一个单独的 Vue.js 客户端旨在使用它。

模型是实体。 GET 请求可以很好地查看数据库中所有实体的索引。但是,当我尝试 POST 一个新实体时,我在控制台中收到以下错误:

Access to XMLHttpRequest at 'http://localhost:3000/entities' from origin > 'http://localhost:8080' 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.

在 rails 应用程序中,我安装了 rack-cors gem 并且在 initializers/cors.rb:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:3000'
    resource '*',
      headers: :any,
      methods: %i(get post put patch delete options head)
  end
end

在routes.rb中:

Rails.application.routes.draw do
  # For details on the DSL...
  post 'auth/login', to: 'authentication#authenticate'
  post 'signup', to: 'users#create'

  resources :entities do
    resources :transactions
  end
end

在客户层:

src/services/Api.js:

import axios from 'axios'

export default() => {
  return axios.create({
    baseURL: 'http://localhost:3000'
  })
}



src/services/EntitiesService.js:

import Api from '@/services/Api'

export default {
  fetchEntities () {
    return Api().get('/entities')
  },

  addEntity (params) {
    return Api().post('entities', params)
  }
}

src/components/newEntity.vue:

<template>
  <div class="entities">
    <h1>Add Entity</h1>
      <div class="form">
        <div>
          <input type="text" name="title" placeholder="TITLE" v-model="title">
        </div>
        <div>
          <textarea rows="15" cols="15" placeholder="DESCRIPTION" v-model="description"></textarea>
        </div>
        <div>
          <button class="app_entity_btn" @click="addEntity">Add</button>
        </div>
      </div>
  </div>
</template>

<script>
import EntitiesService from '@/services/EntitiesService'
export default {
  name: 'NewEntity',
  data () {
    return {
      title: '',
      description: ''
    }
  },
  methods: {
    async addEntity () {
      await EntitiesService.addEntity({
        title: this.title,
        description: this.description
      })
      this.$router.push({ name: 'Entities' })
    }
  }
}
</script>
<style type="text/css">
.form input, .form textarea {
  width: 500px;
  padding: 10px;
  border: 1px solid #e0dede;
  outline: none;
  font-size: 12px;
}
.form div {
  margin: 20px;
}
.app_entity_btn {
  background: #4d7ef7;
  color: #fff;
  padding: 10px 80px;
  text-transform: uppercase;
  font-size: 12px;
  font-weight: bold;
  width: 520px;
  border: none;
  cursor: pointer;
}
</style>

这里有什么问题?

显然在请求中包含 headers 后现在可以正常工作了...

这是新的请求:

src/services/Api.js

  import axios from 'axios'

    export default() => {
      return axios.create({
        baseURL: 'http://localhost:3000',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Access-Control-Allow-Origin': '*'
        }
      })
    }