错误:在express.js应用程序中发送标头后无法设置标头

时间:2014-01-22 21:56:24

标签: node.js express coffeescript

我正在运行一个express.js应用程序,其中我有一个返回json对象的路由

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

在我的控制器文件夹中,我有chapters.coffee文件,如下所示

# 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}

可以在https://github.com/TZM/tzm-blade/blob/master/app/controllers/chapters.coffee

找到代码

为什么我尝试从不同的站点访问章节json文件,我得到:

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.

我如何在我的代码中启用它,并且有更好的方法来执行此操作,因为我也在footer.blade文件中使用它,我也在我的apps.coffee文件中读取了chapters.json文件{{3 }}

非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

首先阅读CORS

然后安装cors

的Express中间件