У меня есть фронт HTML/CSS/JS, который получает местоположение пользователя, когда страница загружается. Он также должен получить записи в моем API Rails. Это ответ, который я получаю в ответе на запрос на выборку {тип: «cors», url: «http: // localhost: 3000/moods», перенаправлен: ложь, статус: 200, ok: true, statustext: «ok», заголовки: заголовки (3), Body: readablem Данные: < /p>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
}
else {
err.innerHTML = "Geolocation is not supported by this browser.";
}
return location;
}
function success(position) {
currentLocation = [position.coords.latitude, position.coords.longitude]
map.setView(currentLocation, 17);
}
function error(error) {
console.log(error)
err.innerHTML = "Please allow location permission to add a marker to the mood map";
}
function getMoods() {
fetch("http://localhost:3000/moods")
.then(res => console.log(res))
.then(data => console.log(data))
}
// ---------------------------------------------------------------------------------------------
document.addEventListener("DOMContentLoaded", (event) => {
getMoods();
getLocation();
})
< /code>
Это мои Rails Routes.rb: < /p>
My rails routes.rb:Rails.application.routes.draw do
resources :moods
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500.
# Can be used by load balancers and uptime monitors to verify that the app is live.
# get "up" => "rails/health#show", as: :rails_health_check
# Defines the root path route ("/")
# root "posts#index"
end
< /code>
Это мои Rails MoodController.rb: < /p>
class MoodsController < ApplicationController
def index
moods = Mood.all
render json: moods
end
def create
mood = Mood.new(mood_params)
if Mood.exists?(latitude: mood.latitude) and Mood.exists?(longitude: mood.longitude)
render json: { message: "Record already exists" }
elsif mood.save()
render json: mood
else
render json: { message: "Error! Could not save!" }
end
end
private
def mood_params
params.require(:mood).permit(:latitude, :longitude, :mood_description)
end
end
< /code>
Это мой cors.rb: < /p>
# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin Ajax requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "*"
resource "*",
headers: :any,
methods: [ :get, :post, :put, :patch, :delete, :options, :head ]
end
end
< /code>
Я попытался убедиться, что cors.rb настроен правильно и что правильные методы разрешены. Я не знаю, связано ли это, но на моем фронте, когда я нажимаю кнопку, я могу сделать запрос на сообщение и хранить информацию в бэкэнд на рельсах. Вот запрос сообщения: < /p>
fetch("http://localhost:3000/moods", {
method: "POST",
body: JSON.stringify({
latitude: currentLocation[0],
longitude: currentLocation[1],
mood_description: moodDescription
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
< /code>
Я ожидал, что данные метода Fetch будут объектами массива, которые я могу затем сохранить в переменной или сделать с ним все, что я хочу. Вместо этого это не определен. Как я могу заставить свой запрос получить работу?
Подробнее здесь: https://stackoverflow.com/questions/796 ... -rails-api
Почему CORS блокирует мой запрос получить запрос на API Rails? [дублировать] ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение