最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add headers on Nuxt static files response? - Stack Overflow

programmeradmin0浏览0评论

I have a json file on static folder and I'm trying to access it from another web site, but I'm having problem with the CORS.

How can I add headers (like Access-Control-Allow-Origin) on the static files response?

I tried this .js/issues/2554#issuecomment-363795301, but didn't work for static files.

module.exports = function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.setHeader('Access-Control-Allow-Methods', '*');
    next()
}

I have a json file on static folder and I'm trying to access it from another web site, but I'm having problem with the CORS.

How can I add headers (like Access-Control-Allow-Origin) on the static files response?

I tried this https://github.com/nuxt/nuxt.js/issues/2554#issuecomment-363795301, but didn't work for static files.

module.exports = function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.setHeader('Access-Control-Allow-Methods', '*');
    next()
}
Share Improve this question asked Aug 27, 2018 at 17:17 Zack StoneZack Stone 7122 gold badges11 silver badges27 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

Nuxt has a build in render property option, that you can use inside the nuxt.config.js file.

If you want to add Access-Control Headers for static files just use the setHeaders function.

See https://nuxtjs.org/api/configuration-render#static.

In the background Nuxt uses the serve-static package (also for other options).

Example:

render: {
   static: {
     setHeaders(res) {
       res.setHeader('X-Frame-Options', 'ALLOWALL')
       res.setHeader('Access-Control-Allow-Origin', '*')
       res.setHeader('Access-Control-Allow-Methods', 'GET')
       res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
  }
}

If you are using axios to make HTTP calls you might want to use Nuxt version of Axios. There you can easily use option proxy in combination with Proxy Module

发布评论

评论列表(0)

  1. 暂无评论