如何在 Nuxt 静态文件响应中添加标头? [英] How to add headers on Nuxt static files response?

查看:73
本文介绍了如何在 Nuxt 静态文件响应中添加标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在静态文件夹中有一个 json 文件,我正在尝试从另一个网站访问它,但是我遇到了 CORS 问题.

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.

如何在静态文件响应中添加标头(如 Access-Control-Allow-Origin)?

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

我试过这个https://github.com/nuxt/nuxt.js/issues/2554#issuecomment-363795301,但不适用于静态文件.

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()
}

推荐答案

Nuxt 有一个内置的渲染属性选项,你可以在 nuxt.config.js 文件中使用.

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

如果您想为静态文件添加访问控制标头,只需使用 setHeaders 函数.

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

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

在后台 Nuxt 使用 serve-static 包(也用于其他选项).

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

示例:

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')
  }
}

这篇关于如何在 Nuxt 静态文件响应中添加标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆