我在静态文件夹中有一个 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 静态文件响应中添加标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!