0

i am running an express.js application where i have a route that returns a json object

https://serene-depths-3284.herokuapp.com/chapters?setLng=en-UK

in my controllers folder i have chapters.coffee file which is as follows

# Return the chapters.json based on the language
i18n = require "i18next"
fs = require "fs"
cldr = require "cldr"
__ = require "underscore"

exports.chapters = (req, res, err) ->
    fs.readFile "./data/chapters.json", (err, chapterJSON) ->
        console.log("read file error", err) if err
        tzmChapters = JSON.parse chapterJSON
        try
            # ...
            lngCode = req.query.setLng.split("-")[0]
        catch e
            # fallback to user locale
            lngCode = i18n.lng().split("-")[1]
        allCountries = cldr.extractTerritoryDisplayNames(lngCode)
        tzmNetwork = []
        tzm = __.each tzmChapters, (value, index, list) ->
            locale = value.desc.LOCALES.split("-")[1]
            tzmNetwork.push({link:value.desc.WEBSITE,contact:value.desc.CONTACT,country: allCountries[locale]})
        res.json {tzmNetwork}

the code can be found at https://github.com/TZM/tzm-blade/blob/master/app/controllers/chapters.coffee

and why i try to access the chapters json file from a different site, i get:

XMLHttpRequest cannot load http://localhost:3000/chapters. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.

how do i enable this in my code and is there a better way to do this as i am also using it in the footer.blade file and i read the chapters.json file also in my apps.coffee file https://github.com/TZM/tzm-blade/blob/master/app/config/apps.coffee#L163

any advice is much appreciated.

khinester
  • 3,398
  • 9
  • 45
  • 88

1 Answers1

0

First read up on CORS

Then install the Express middleware for cors

Bulkan
  • 2,555
  • 1
  • 20
  • 31