ankane/shorts

navigator.sendBeacon with authenticity token

Closed this issue · 3 comments

Hi Ankane, I was trying the following from the shorts you have here:

https://stackoverflow.com/questions/49946055/handling-csrf-authenticity-token-for-navigator-sendbeacon-requests-in-rails

  $(window).on('unload', function() {
        db.flipCounter.get(gon.slug, function(obj) {
            var payload = {
                slug: gon.slug,
                localFlipCount: obj.fc,
                time: Date.now()
            }

            navigator.sendBeacon('/analytics', csrfProtect(payload))

        })
    })

    function csrfProtect(payload) {
        var param = $("meta[name=csrf-param]").attr("content")
        var token = $("meta[name=csrf-token]").attr("content")

        if (param && token) payload[param] = token
        return new Blob([JSON.stringify(payload)], { type: "application/json; charset=utf-8" })
    }

It throws the following error on client side:

Promise.js:840 Unhandled rejection: TypeError: Cannot create property 'authenticity_token' on string '{"slug":"test-page-by-marvin-danig","localFlipCount":1,"time":1524241435403}'

Never mind, I found the issue.

Stuck at the controller level. I noticed there is ahoy_matey for rails but I wanted to keep this light and save just a simple flipCount data as per code above.

Rails isn't accepting the authenticity_token this way however. :-(

Processing by BooksController#analytics as */*
  Parameters: {"{\"slug\":\"test-page-by-marvin-danig\",\"localFlipCount\":1,\"time\":1524243279653,\"param\":\"8rzDx/TNL8YeU1/NWgWSk6gB/UvmbB9Ip VajDCgfDUv5Q4pjh7x0GUG1il1jDJajtJyHf84Xv5Pt14fiCnA9w"=>"=\"}"}
Can't verify CSRF token authenticity.
exception
ActionController::InvalidAuthenticityToken
  Rendering public/500.html
  Rendered public/500.html (0.6ms)
Completed 500 Internal Server Error in 316ms (Views: 315.2ms | ActiveRecord: 0.0ms)

Hey @marvindanig, this isn't a great place to get help debugging issues. I'd try Stack Overflow.