フロント
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>besukosan</title>
</head>
<body>
<h1 id="hoge"></h1>
<script src="index.js"></script>
</body>
</html>
index.js
const utc = new Date().getTime();
const sec = -60 * 1000 * new Date().getTimezoneOffset();
// 適切に変える
const url = 'http://localhost:3000/hello';
fetch(url, {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ time: new Date(utc + sec) }),
})
.then(async res => {
const _ret = await res.json();
const _now = new Date(_ret['time']);
const _time = `${_now.getUTCFullYear()}-${
_now.getUTCMonth() + 1
}-${_now.getUTCDate()}-${_now.getUTCHours()}:${_now.getUTCMinutes()}:${_now.getUTCSeconds()}`;
document.getElementById('hoge').textContent = _time;
console.log(_time);
})
.catch(console.error);
バックエンド(一部省略)
app/controllers/hello_controller.rb
class HelloController < ApplicationController
protect_from_forgery except: :helo
def helo
time_i = Time.parse(params["time"]).to_i
date = Time.at(time_i).utc
p date.year.to_s + "-" + date.mon.to_s + "-" + date.day.to_s + "-" + date.hour.to_s + ":" + date.min.to_s + ":" + date.sec.to_s
render json: { time: params["time"] }
end
end
config/application.rb
# 省略
module Myproject
class Application < Rails::Application
# 省略
config.middleware.insert_before 0, Rack::Cors do
allow do
origins "*"
resource "*",
headers: :any,
methods: [:get, :post, :options, :head]
end
end
end
end
config/routes.rb
Rails.application.routes.draw do
post "/hello", to: "hello#helo"
end
.Gemfile
# 省略
gem "rack-cors"
# 省略
Like!