My name is yuki. Thanks to DMMWEBCAMP, I am now working as a WEB engineer, gathering my friends to develop services, tutoring programming, and enjoying my engineer life every day.
We also provide support and error questions for those who are aiming from inexperienced, so if you are interested, please contact DM.
I had a problem when I was using Rails as an API and was collecting images using gem twitter
.
The URI of the image acquired by the twitter API starts with http
, and a warning of" unsafe "has appeared on the site where https communication is possible.
By the way, at that time, I was getting this error on the console.
Mixed Content: The page at 'https://hogehoge.com' was loaded over HTTPS, but requested an insecure image 'http://hogehoge.net/hoge.jpg. This content should also be served over HTTPS.
It seems to be called mixed content. At first, I couldn't think of a way to put it together this time, so I managed to do it at the front desk, but I fixed it because it should be done at the back.
examples_controller.rb
def show
client = Authorization.init #This is a unique class. Contains client information.
@data = client.search("#Hashtags you want to collect", result_type: "recent").take(4).collect do |tweet|
{
"image": "#{tweet.user.profile_image_url.to_s.sub('http', 'https')}",
"name": "#{tweet.user.name}",
"text": "#{tweet.full_text}",
"tweet_link": "#{tweet.uri}"
}
end
render json: {tweet: @data}
end
To explain what I'm doing, I collect 4 tweets with a specific hashtag and return them as json data.
The important part this time is " image ":" # {tweet.user.profile_image_url.to_s.sub ('http','https')} ",
.
This was taught by another engineer, but when I look at ʻuser.profile_image_url` on the rails console, the result is returned in the form of data (?) That I do not understand a little, but by to_s It became a beautiful URL.
It feels like I'm converting by applying the sub method there.
Note that you are using sub instead of gsub. The reason is that if there is a character string "http" in a part (other than the beginning) of the URL of the image, it will be converted incorrectly and the image will not be displayed.
I hope it helps someone.
Recommended Posts