I have an HTML/CSS/JS frontend that gets the user’s location when the page loads. It should also be getting the records in my Rails API. This is the response I get in the fetch request Response { type: "cors", url: "http://localhost:3000/moods", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers(3), body: ReadableStream, bodyUsed: false } index.js:34:24 The following is my frontend code to get location and fetch data:
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();
})
This is my rails routes.rb:
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
This is my rails MoodController.rb:
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
This is my cors.rb:
# 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
I have tried making sure that the cors.rb is configured correctly and that the correct methods are being allowed. I don’t know if this is related, but in my frontend, when I click a button, I am able to make a POST request and store information in my rails backend. Here is the POST request:
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"
}
});
I expected the fetch method’s data to be an array objects that I can then store in a variable or do whatever I want with it. Instead it is undefined. How can I get my GET request to work?