ruby-on-rails - 使用 Rails,我应该如何配置我的 application.rb 以允许 CORS 请求发生?
问题描述
我使用 Rails 作为后端 API 来支持使用 VueJS 制作的前端。我想在网站上按下按钮时从 VueJS 发送 POST 请求,我使用 axios 来执行此操作
`
methods: {
// Performs a POST request to the rails endpoint and passes the email and pass as parameters
signup() {
if (this.password === this.password_confirmation) {
this.$http.plain
.post("/signup", {
email: this.email,
password: this.password,
password_confirmation: this.password_confirmation
})
// If successful execute signinSuccesful
.then(response => this.signinSuccesful(response))
// If it doesn't run for whatever reason, execute signupFailed
.catch(error => this.signinFailed(error));
}
},`
理论上,这应该创建一个 API 接收的 POST 请求,我试图像这样捕获请求:post "signup", controller: :signup, action: :create
但是,当我在 chrome 上查看控制台时,我在第一次加载网站时遇到错误:
`0/signin net::ERR_CONNECTION_REFUSED`
当我单击按钮发送 POST 请求时出现另一个错误:*
从源“ http://localhost:8080 ”访问“ http://localhost:3000/signup ”的 XMLHttpRequest已被 CORS 策略阻止:Access-Control-Allow-Headers 不允许请求标头字段内容类型在预检响应中。
我的“application.rb”文件如下所示:
`module RecordstoreBackend
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.api_only = true
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :patch, :put, :delete, :post, :options]
end
end`
我认为问题是这个文件,但我不知道如何配置它。谢谢你的帮助。
解决方案
在我看来,您似乎缺少该请求的主机(在您的 Vue 应用程序上)。请注意,错误0/signup
表明它正在向它发送请求,http://0/signup
这反过来又“拒绝”了连接。
我不熟悉 Vue.js 结构,但我建议将 axios 调用封装在将使用host
来自环境配置文件的插件上,以便您可以为 localhost 和生产环境使用不同的主机。甚至只是将主机添加到您的环境中:
methods: {
// Performs a POST request to the rails endpoint and passes the email and pass as parameters
signup() {
if (this.password === this.password_confirmation) {
this.$http.plain
.post(`${process.env.API_HOST}/signup`, {
email: this.email,
password: this.password,
password_confirmation: this.password_confirmation
})
// If successful execute signinSuccesful
.then(response => this.signinSuccesful(response))
// If it doesn't run for whatever reason, execute signupFailed
.catch(error => this.signinFailed(error));
}
},
参考:https ://cli.vuejs.org/guide/mode-and-env.html#environment-variables
如果您想以现在的方式修复它,只需将您的主机添加到 axios 调用中:
methods: {
// Performs a POST request to the rails endpoint and passes the email and pass as parameters
signup() {
if (this.password === this.password_confirmation) {
this.$http.plain
.post("http://localhost:3000/signup", {
email: this.email,
password: this.password,
password_confirmation: this.password_confirmation
})
// If successful execute signinSuccesful
.then(response => this.signinSuccesful(response))
// If it doesn't run for whatever reason, execute signupFailed
.catch(error => this.signinFailed(error));
}
},
关于 CORS 错误,请检查:https ://stackoverflow.com/a/25727411/715444