0

I am storing some json data in an active-record session so have created a route and controller action which renders fine in the browser but when I try and pass the route into a JavaScript function the response in browser(chrome) network tab is null

Controller

class DataFilesController < ApplicationController
  def show
    render json: session[:my_data]
  end
end

Route

get 'data-file.json', to: 'data_files#show', as: :data_file

Javascript function (in view)

= content_for :javascript do
  :javascript
    accessibleAutocomplete({
      element: document.querySelector('#autocomplete-wrapper'),
      id: 'autocomplete',
      source: openregisterPickerEngine({
        url: "<%= data_file_path %>"
      }),
      templates: {
        inputValue: inputValueTemplate,
        suggestion: suggestionTemplate
      }
    });
4
  • What response is null? On the Rails side (your server logs, your Browser's Network tab, do you see the request and response you were expecting? Commented Aug 25, 2017 at 15:57
  • is accessibleAutocomplete function similar to ajax call? is this you defined function? Commented Aug 25, 2017 at 16:25
  • Add more information Commented Aug 25, 2017 at 16:25
  • Response when I check the network tab in Chrome inspector. Commented Aug 25, 2017 at 20:44

1 Answer 1

2

The openregisterPickerEngine library uses the fetch Request object, which by default does not send cookies. This means that your DataFilesController endpoint does not get the session ID in the users cookie and the session object is null.

Request.credentials needs to be set: https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

Unfortunately the Request object is created in the library code which you don't directly control: https://github.com/alphagov/openregister-picker-engine/blob/master/src/index.js#L294

You either need to redesign the code so that the data endpoint does not need the session, or fork or modify that library (or stop using the library and craft your own fetching and parsing code).

Edit: actually the latest version of the library uses xhr while the older version you were using calls fetch. So the simplest "solution" is to upgrade the library: unlike fetch, xhr sends cookies with same-origin requests by default.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.