无法从控制台获取,但可以从地址栏获取



我正在设置Rails API,无法从控制台获取数据,即使我可以通过地址栏检索数据。在控制台中,我不断收到一个错误:

TypeError: Failed to fetch at <anonymous>:1:1

当我从地址栏发出HTTP请求时,我能够毫无问题地检索数据。我正在使用一个序列化程序,它工作正常

这是我的获取GET请求:

fetch('http://localhost:3000/api/v1/users')
.then(res => res.json())
.then(data => console.log)

以下是回复:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Failed to fetch at <anonymous>:1:1

这是我的索引操作:

def index
users = User.all
render json: UserSerializer.new(users)
end

以下是我的路线:

namespace :api do
namespace :v1 do
resources :users, only: [:index, :create]
post '/login', to: 'auth#create'
get '/profile', to: 'users#profile'
end
end

这是我的序列化程序:

class UserSerializer
include FastJsonapi::ObjectSerializer
attributes :username, :email, :password, :role
end

当我从地址栏发出相同的GET请求时,我得到了正确的响应:

// 20211108121639
// http://localhost:3000/api/v1/users
{
"data": [
{
"id": "1",
"type": "user",
"attributes": {
"username": "mlgvla",
"email": "monica@test.com",
"password": null,
"role": "student"
}
}
]
}

我已经尝试将端口更改为3001,结果完全相同。我对很久以前发生的这种奇怪事情有一些模糊的记忆,但我忘记了发生这种事情的原因。

感谢您为解决这一问题提供的指导和智慧。显然,在我知道可以使用fetch执行GET或POST之前,我无法设置我的前端!

这可能与CORS安全性有关。在我看来,你不能用这种方式直接打电话到后端。当您直接键入URL时,它会起作用,因为它是由Rails处理的

试试这个宝石,它应该会帮助你:RACK CORS gem

捆绑安装

然后添加config/ininitializers/cors.rb:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :patch, :put]
end
end

为了更安全,您应该限制来源:-(

最新更新