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

查看:532
本文介绍了如何在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天全站免登陆